Sword refers to offer—55_2. Balanced Binary Tree—Analysis and Code (Java)

Sword refers to offer-55_2. Balanced binary tree-analysis and code [Java]

1. Title

Enter a binary tree to determine whether the binary tree is a balanced binary tree.
Here, we only need to consider its balance, not whether it is a sorted binary tree.

Two, analysis and code

1. Record the depth

(1) Thinking

If the difference between the left and right subtrees of any node in a binary tree does not exceed 1, then it is a balanced binary tree.
You can avoid repeated recursion by recording the depth of each node. Further, for each node, the depth of its left and right subtrees can be recorded first, and whether it is balanced, and then its own depth can be calculated. According to the characteristics of this process, the method of post-order traversal can be selected.

(2) Code

public class Solution {
    
    
    public boolean IsBalanced_Solution(TreeNode root) {
    
    
        return TreeDepth(root) == -1 ? false : true;
    }
     
    public int TreeDepth(TreeNode root) {
    
    
        if (root == null)
            return 0;
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        if (left == -1 || right == -1 || left - right > 1 || right - left > 1)
            return -1;
        return Math.max(left, right) + 1;
    }
}

(3) Results

Running time: 11 ms, occupying 9440 k of memory.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/111561863