剑指offer:平衡二叉树

题目描述

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

 

AC C++ Solution:

递归判断左右子树的高度差并记录高度返回给父节点

class Solution {
public:
    int dfs(TreeNode* pRoot) {
        if(pRoot == NULL)
            return 0;
        
        int leftheight = dfs(pRoot->left);
        if(leftheight == -1)
            return -1;
        
        int rightheight = dfs(pRoot->right);
        if(rightheight == -1)
            return -1;
        
        if(abs(leftheight - rightheight) > 1)
            return -1;
        
        return max(leftheight,rightheight) + 1;
    }
    
    
    bool IsBalanced_Solution(TreeNode* pRoot) {
        return dfs(pRoot) != -1;
    }
    
};

 

展开阅读全文

没有更多推荐了,返回首页