码迷,mamicode.com
首页 > 其他好文 > 详细

剑指OFFER 平衡二叉树

时间:2020-02-06 20:08:55      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:roo   二叉树   它的   代码   void   ret   int   nod   ==   

剑指OFFER 平衡二叉树

分析

先理解什么是平衡二叉树

它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

下面的代码我只判断了根节点左右孩子的深度(没有再递归判断其子树的),但是也一样过了.

代码

class Solution {
public:
    
    int left_depth = 0;
    int right_depth = 0;
    int* p_depth = NULL;
    
    void recur(TreeNode* node,int depth)
    {
        if(node == NULL)return ;
        
        if(depth>*p_depth)*p_depth=depth;
        
        recur(node->left,depth+1);
        recur(node->right,depth+1);
    }
    
    bool IsBalanced_Solution(TreeNode* root) {
        if(root == NULL)return true;
        p_depth = &left_depth;
        recur(root->left,1);
        p_depth = &right_depth;
        recur(root->right,1);
        return !(abs(left_depth-right_depth)>1);
    }
};

剑指OFFER 平衡二叉树

标签:roo   二叉树   它的   代码   void   ret   int   nod   ==   

原文地址:https://www.cnblogs.com/virgildevil/p/12269886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!