Simple C++ code. DFS


  • 0
    N
    /**
     * 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 isB=true;
        int height(TreeNode* root)
        {
            if(root==NULL)return 0;
            int left=(height(root->left)+1);
            int right=(height(root->right)+1);
            if(left-right>1||left-right<-1)isB=false;
            return max(left,right);
        }
        bool isBalanced(TreeNode* root) {
            if(root==NULL)return true;
            height(root);
            return isB;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.