剑指offer编程题--判断是否为平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路

递归思想。先看根节点是否是平衡的,再看左右子树是否是平衡的。如果都是平衡的,则整个树就是平衡的。

平衡的判别条件是,左右子树的深度之差不超过1

至于深度的计算,刚好就用到了前面一题求二叉树的深度了~

Java代码

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null){
            return true;
        }
        int left = treeDeep(root.left);
        int right = treeDeep(root.right);
        if(left-right>1||left-right<-1){
            return false;
        }
        return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);

    }
    public int treeDeep(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = treeDeep(root.left);
        int right = treeDeep(root.right);
        return 1+(left>right?left:right);
    }
}

C++代码

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot == NULL){
            return true;
        }
        int ld = treeDeep(pRoot->left);
        int rd = treeDeep(pRoot->right);
        int cha = ld - rd;
        if(cha>1||cha<-1){
            return false;
        }
        return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
    }
    int treeDeep(TreeNode* pRoot){
        if(pRoot == NULL){
            return 0;
        }
        int ld = treeDeep(pRoot->left);
        int rd = treeDeep(pRoot->right);
        return 1+(ld>rd?ld:rd);
    }
};
点赞