[LeetCode]Balanced Binary Tree

来源:互联网 发布:200鼠标推荐知乎 编辑:程序博客网 时间:2024/06/05 23:58

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.

这道题以前整理过,这里就不细写了,直接贴上代码:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool fun(TreeNode* root,int& depth){        if(root==NULL){            depth=0;            return true;        }        int left,right;        if(fun(root->left,left)&&fun(root->right,right)){            int diff=left-right;            if(abs(diff)<=1){                depth=1+(left>right?left:right);                return true;            }        }        return false;    }    bool isBalanced(TreeNode *root) {        int depth=0;        return fun(root,depth);    }};

下面是以前整理的链接:平衡二叉树的判断

0 0
原创粉丝点击