[Leetcode] Balanced Binary Tree

来源:互联网 发布:怎样用软件阅读趣头条 编辑:程序博客网 时间:2024/05/01 06:43

Given a binary tree, determine if it is height-balanced.For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.c

class Solution {public:    bool isBalanced(TreeNode* root) {        int depth = 0;        return isBalancedHelper(root, &depth);    }        bool isBalancedHelper(TreeNode* root, int* depth){        if(root == nullptr){            *depth = 0;            return true;        }        else {            int depth1 = 0;            int depth2 = 0;            bool subtree_result = isBalancedHelper(root->left, &depth1) && isBalancedHelper(root->right, &depth2);            *depth = max(depth1, depth2) + 1;            return abs(depth1 - depth2) <= 1 && subtree_result;        }    }};

递归求是否为balanced的同时求高度

0 0
原创粉丝点击