Seeking to prove safety offer- depth of the tree

Title Description

Input binary tree, find the depth of the tree. Forming a path tree from the root node to the leaf node sequentially passes (including the root, leaf nodes), the depth of the length of the longest path in the tree.

Thinking

Recursively. Find the longest road, plus the current equivalent of the root node, and then select the deepest way in from the left and right sub-tree.

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def TreeDepth(self, pRoot):
        if pRoot:
            return self.getPathLength(pRoot,0)
        else:
            return 0
    def getPathLength(self,root,length):
        if root:
            length+=1
            length = max([self.getPathLength(root.left,length),self.getPathLength(root.right,length)])
        return length

 

This is similar to the following questions

Title Description

Input binary tree, the binary tree is determined whether a balanced binary tree.

Thinking

Defined balanced binary tree, the difference between left and right subtrees depth of not more than 1, and the left and right subtrees are balanced binary tree

I still use recursion. Recursive process found around sub-tree depth difference of more than 1, and returns False, otherwise depth. ps: we should pay attention here to the beginning of time, set a depth of 1. Otherwise there is no way based on the return value of the function of judge, in the end it is a depth of 0, or returns False

class Solution:
    def IsBalanced_Solution(self, pRoot):
        if not pRoot:
            return True
        else:
            depth = self.getDepth(pRoot,1)
            if not depth:
                return False
            else:
                return True
            
    def getDepth(self,root,length):
        if root:
            length += 1
            left = self.getDepth(root.left,length)
            right = self.getDepth(root.right,length)
            if not left or not right:
                return False
            elif abs(left-right)>1:
                return False
            else:
                length = max([left,right])
        return length

 

Published 82 original articles · won praise 2 · Views 4354

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104815880