欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Day34: [LeetCode简单] 110. 平衡二叉树

程序员文章站 2022-03-15 20:36:11
...

Day34: [LeetCode简单] 110. 平衡二叉树

题源:

来自leetcode题库:

https://leetcode-cn.com/problems/balanced-binary-tree/

代码:

dirty code凑合看吧

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool flag;
    int f(TreeNode* root){
        if(flag==false) return -1;
        if(root){
            int x=f(root->left),y=f(root->right);
            if(x-y>1||y-x>1) flag=false;
            return (x>y?x:y)+1;
        }else{
            return 0;
        }
    }
    bool isBalanced(TreeNode* root) {
        if(!root) return 1;
        flag=true;
        f(root);
        return flag;
    }
};