剑指offer 平衡二叉树

来源:互联网 发布:mr数据与信令相关联 编辑:程序博客网 时间:2024/05/22 13:30

题目描述:

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

思路:在得到树的高度之后,对左右树的高度进行判断,如果绝对值之差大于1则不是平衡二叉树。

代码:

class Solution {public:    bool ok = true;    int abs(int a,int b)    {        if(a>b)  return a-b;        else     return b-a;    }    bool IsBalanced_Solution(TreeNode* pRoot)     {        if(!pRoot) return true;        int ans = dfs(pRoot);        return ok;    }    int dfs(TreeNode* pRoot)    {        if(!pRoot) return 0;        int left_depth = dfs(pRoot->left);        int right_depth = dfs(pRoot->right);     if(abs(left_depth,right_depth)>1)  ok = false;        return left_depth>right_depth?left_depth+1:right_depth+1;    }};


原创粉丝点击