Skip to content

Latest commit

 

History

History
executable file
·
85 lines (43 loc) · 2.83 KB

110. Balanced Binary Tree.md

File metadata and controls

executable file
·
85 lines (43 loc) · 2.83 KB

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

##(一)题目

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two >subtrees of every node never differ by more than 1.

##(二)解题

题目大意:判断一个二叉树是不是高度平衡二叉树

解题思路:所谓高度平衡,就是左右子树的高度差不超过1。

可以采用递归的思想,判断一个二叉树是不是平衡二叉树,需要判断它的左右子树是不是平衡二叉树,依次递归下去。

也就是说,把二叉树的每一个节点都当做根节点,判断它的左右子树是否平衡。

那么,当前节点的左右子树的高度,应该等于左右子树中较高的那个子树的高度加上1。

当根节点为NULL的时候直接返回0.

具体解释见代码:

/**

 * Definition for a binary tree node.

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    bool isBalanced(TreeNode* root) {

        return dfsTree(root)!=-1;

    }

    int dfsTree(TreeNode* root)

    {

        if(root==NULL) return 0;//空节点返回0

        int left = dfsTree(root->left);//求左子树的高度

        if(left == -1) return -1;//-1代表不平衡

        int right = dfsTree(root->right);//求右子树的高度

        if(right== -1) return -1;//-1代表不平衡

        if(abs(left-right)>1) return -1;///如果不平衡则返回-1

        return max(left,right)+1;//否则返回较高的那一个加上1

    }

};