Leetcode之Balanced Binary Tree

题目:

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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

代码:

/**
 * 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:
   int helper(TreeNode* root) {
	if (!root)return 0;
	int left = helper(root->left);
	int right = helper(root->right);
	
	int a = abs(left - right);
	if (a > 1 || left == -1 || right == -1)return -1;
	return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) {
	
	if (helper(root) == -1)return false;
	return true;
}
};

猜你喜欢

转载自blog.csdn.net/qq_35455503/article/details/91410338