首页 > 代码库 > Balanced Binary Tree

Balanced Binary Tree

问题:判断二叉树是否为平衡二叉树
分析:树上的任意结点的左右子树高度差不超过1,则为平衡二叉树。
         搜索递归,记录i结点的左子树高度h1和右子树高度h2,则i结点的高度为max(h1,h2)=1,|h1-h2|>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:    int flag=true;    int dfs(TreeNode *root)    {         if(root==NULL) return true;         int h1,h2;         if(root->left==NULL) h1=0;         else h1=dfs(root->left);         if(root->right==NULL) h2=0;         else h2=dfs(root->right);         if(abs(h1-h2)>1) flag=0;         return max(h1,h2)+1;    }    bool isBalanced(TreeNode *root) {        dfs(root);        return flag;    }};