leetcode_Balanced Binary Tree

来源:互联网 发布:js页面切换动画效果 编辑:程序博客网 时间:2024/05/10 06:45
class Solution {public:    int diff=-1;    int maxDiff(TreeNode * root)    {        int ldepth=0,rdepth=0;        if(root==NULL) return 1;        if(root->left!=NULL) ldepth=maxDiff(root->left)+1;        if(root->right!=NULL) rdepth=maxDiff(root->right)+1;        if(diff<ldepth-rdepth) diff=ldepth-rdepth;        if(diff<rdepth-ldepth) diff=rdepth-ldepth;        return ldepth>rdepth?ldepth:rdepth;    }    bool isBalanced(TreeNode* root) {        if(root==NULL) return true;        maxDiff(root);        if(diff>=2) return false;        return true;    }};

题目链接:https://leetcode.com/problems/balanced-binary-tree/

要注意代码规范if(root->left)是错的,一定要写成if(root->left!=NULL)

0 0
原创粉丝点击