[LeetCode] Balanced Binary Tree

来源:互联网 发布:开机svchost.exe无网络 编辑:程序博客网 时间:2024/05/21 10:45

问题:

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.

分析:

又见Binary tree,又是递归。

代码:

class Solution {public:int isBalancedHelper(TreeNode *root) {if (!root) return 0;int left = isBalancedHelper(root->left);int right = isBalancedHelper(root->right);if (left == -1 || right == -1) return -1;if (left - right <= 1 && right - left <= 1)return max(left, right) + 1;elsereturn -1;}bool isBalanced(TreeNode *root) {return isBalancedHelper(root) != -1;}};


0 0
原创粉丝点击