当前位置:网站首页>[Niuke brush questions day4] jz55 depth of binary tree

[Niuke brush questions day4] jz55 depth of binary tree

2022-07-05 08:43:00 strawberry47

subject :

Enter a binary tree , Find the depth of the tree . The nodes that pass from the root node to the leaf node ( Containing root 、 leaf ) A path to a tree , The length of the longest path is the depth of the tree , The depth of the root node is treated as 1 .
 Insert picture description here

Ideas :

First encounter the problem of trees , A little confused , I don't understand his construction process
The first reaction is to use recursion , Because the end condition is easy to think of : Both left and right nodes are empty
but, I don't know how to move the root node ...

answer :

Looking at the answer , The idea of recursion is also used :
mentally .. Recursion is so hard o(╥﹏╥)o

class Solution:
    def TreeDepth(self , pRoot: TreeNode) -> int:
        # write code here
        if not pRoot:
            return 0
        left = right =0
        if pRoot.left:
            left = self.TreeDepth(pRoot.left)
        if pRoot.right:
            right = self.TreeDepth(pRoot.right)
        return max([left,right])+1

You can also use the idea of queues :

import queue
class Solution:
    def maxDepth(self , root: TreeNode) -> int:
        #  Empty nodes have no depth 
        if not root: 
            return 0
        #  Subsequent nodes of the queue maintenance hierarchy 
        q= queue.Queue() 
        #  Root in the team 
        q.put(root) 
        #  Record the depth 
        res = 0
        #  Level traversal 
        while not q.empty(): 
            #  Record how many nodes there are in the current layer 
            n = q.qsize() 
            #  Traverse this layer , Go on to the next floor 
            for i in range(n): 
                node = q.get()
                #  Add the left and right nodes of the next layer 
                if node.left: 
                    q.put(node.left)
                if node.right:
                    q.put(node.right)
            #  Depth plus 1
            res += 1 
        return res
 

The idea of queue is easier to understand , Is to save every layer , See how many layers you can save , Plus one

原网站

版权声明
本文为[strawberry47]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050839174870.html