Likou brushing notes: 110. Balanced binary tree (depth-first search dfs, must be able to understand)

topic:

110, balanced binary tree

Given a binary tree, judge whether it is a highly balanced binary tree.

In this question, a highly balanced binary tree is defined as:

The absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1.

Example 1:
Insert picture description here

Input: root = [3,9,20,null,null,15,7]
Output: true

Example 2:

Insert picture description here

Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

Example 3:

Input: root = []
Output: true

prompt:

The number of nodes in the tree is in the range [0, 5000]
-10^4 <= Node.val <= 10^4

Problem solution ideas:

Since a balanced binary tree is defined as ** the absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1. **Described in pseudo code is:

if abs(高度(root.left) - 高度(root.right)) <= 1 and root.left 也是平衡二叉树 and root.right 也是平衡二叉树:
    print('是平衡二叉树')
else:
    print('不是平衡二叉树')

And how root.left and root.right judge whether it is a binary balanced tree is the same as root. It can be seen that this problem is obviously recursive.

So we first need to know how to calculate the height of a subtree. This can be easily calculated recursively. The Python code for calculating the height of the subtree is as follows:

def dfs(node, depth):
    if not node: return 0
    l = dfs(node.left, depth + 1)
    r = dfs(node.right, depth + 1)
    return max(l, r) + 1

Complexity analysis

Time complexity: For isBalanced, since each node is visited at most once, the time complexity of this part is O(N), and the number of times the dfs function is called each time does not exceed log N, so the total time complexity It is O(NlogN), where N is the total number of nodes in the tree.

Space complexity: Due to the use of recursion, the bottleneck of space complexity here is the stack space, so the space complexity is O(h), where h is the height of the tree.

Problem solution python code:

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        def dfs(node, depth):
            if not node: return 0
            l = dfs(node.left, depth + 1)
            r = dfs(node.right, depth + 1)
            return max(l, r)  + 1

        if not root: return True
        if abs(dfs(root.left, 0)-dfs(root.right, 0))>1: return False

        return self.isBalanced(root.left) and self.isBalanced(root.right)

Author: fe-lucifer
link: https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-zhuan-ti-by-fe-lucifer/
Source: force LeetCode (LeetCode) https://leetcode-cn.com/problems/balanced-binary-tree/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114680725