Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

python - What is actually the definition of the root (the input) of a tree

I am kind of new in date structure.

In some Leetcode problems, the input given is say root = [1,2,3,4,5,null,6,7,null] and the type of root is TreeNode which seems to be a single node as follow

class TreeNode:
     def __init__(self, val=0, left=None, right=None):
         self.val = val
         self.left = left
         self.right = right

But the input here is clearly a "list": root = [1,2,3,4,5,null,6,7,null]

When I create a recursive function and it takes root as the input and maybe returns an integer, does it automatically start dealing with the first element in this tree even though the root here is a "tree" of elements? It seems to me many such functions call root and use it as a single variable (or node) instead of the entire tree which makes me confused sometimes. For example

def afunction(self, root: TreeNode) -> int:
    
        queu = [root]
        maxDepth = float('-inf')
        result = 0
        .....

The root here seems to be a node which doesn't really contain a value? And how to store it as queu = [root]?

question from:https://stackoverflow.com/questions/65860298/what-is-actually-the-definition-of-the-root-the-input-of-a-tree

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The list likely represents a tree where the node at index i has its two children at indices 2*i + 1 and 2*i + 2. Your given list then represents the tree

                      1
                    (i=0)
                    /   
                  2      3
                (i=1)  (i=2)
                /         
              4      5      6 
            (i=3)  (i=4)  (i=6)
            /
           7
         (i=7) 

Under this interpretation, there's little distinction between the root and the tree rooted at the root node. Note, though, that a subtree is not a single slice of the tree, and concatenating two trees under a single root node does not correspond to simple list concatenation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...