头图

title: Daily practice (28): Balanced binary tree

categories:[Swords offer]

tags:[Daily practice]

date: 2022/03/01


Daily practice (28): Balanced binary tree

Enter the root node of a binary tree to determine whether the tree is a balanced binary tree. If the depths of the left and right subtrees of any node in a binary tree do not differ by more than 1, then it is a balanced binary tree.

Example 1:

Given a binary tree [3,9,20,null,null,15,7]

 3
/ \
9  20
/  \
15   7

Return true.

Example 2:

Given a binary tree [1,2,2,3,3,null,null,4,4]

   1
  / \
 2   2
 / \
3   3
 / \
4   4

Return false.

limit:

0 <= the number of nodes in the tree <= 10000

Source: LeetCode

Link: https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof

Method 1: Post-order traversal (DFS)

DFS calculation ideas:

  • For empty nodes, the depth is 0
  • The current depth is the maximum value of the depth of the left and right subtrees + 1, and the depth is directly returned in valid cases
  • Once the depth difference between the left and right subtrees is found to exceed 1, it is considered invalid and returns -1
  • Once it is found that the return is -1, return -1 directly
bool isBalanced(TreeNode* root) {
    return (dfs(root) != -1);
}
int dfs(TreeNode* node) {
    if (node == nullptr) {
        return 0;
    }
    int left = dfs(node->left);
    if (left == -1) {
        return -1;
    }
    int right = dfs(node->right);
    if (right == -1) {
        return -1;
    }
    return abs(left - right) > 1 ? -1 : max(left, right) + 1;//当前深度是左右子树深度的最大值+1, 有效情况直接返回深度
}

Method 2: Preorder traversal

For the currently traversed node, first calculate the height of the left and right subtrees. If the height difference between the left and right subtrees does not exceed 11, then recursively traverse the left and right subtrees respectively, and determine whether the left subtree and the right subtree are balanced. This

is a top-down recursive process

int height(TreeNode* root) {
    if (root == nullptr) {
        return 0;
    }
    return max(height(root->left), height(root->right)) + 1;
}
bool isBalanced(TreeNode* root) {
    if (root == nullptr) {
        return true;
    }
    return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记