LeetCode 110. Balanced Binary Tree

原题链接在这里:https://leetcode.com/problems/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 left and right subtrees of every node differ in height by no 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.

题解:

Get 最大深度.如果左右最大深度相差大于一,则返回-1. 若是已有左或者右的返回值为-1, 即返回-1.

最后看返回到root时是否为一个负数,若是负数则不是balanced, 若是正数,则返回了最大深度,是balanced.

Time Complexity: O(n).

Space: O(log n), n is number of nodes in the tree.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isBalanced(TreeNode root) {
12         return maxDepth(root) >= 0; 
13     }
14     
15     private int maxDepth(TreeNode root){
16         if(root == null){
17             return 0;
18         }
19         int leftDepth = maxDepth(root.left);
20         int rightDepth = maxDepth(root.right);
21         if(leftDepth == -1 || rightDepth == -1 || Math.abs(leftDepth - rightDepth) > 1){
22             return -1;
23         }
24         return Math.max(leftDepth, rightDepth) + 1;
25     }
26 }

AC C++:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     bool isBalanced(TreeNode* root) {
15         return maxDepth(root) >= 0;
16     }
17 
18     int maxDepth(TreeNode* root){
19         if(!root){
20             return 0;
21         }
22 
23         int l = maxDepth(root->left);
24         int r = maxDepth(root->right);
25         if(l < 0 || r < 0 || abs(l - r) > 1){
26             return -1;
27         }
28 
29         return max(l, r) + 1;
30     }
31 };

类似Maximum Depth of Binary Tree.  

posted @ 2015-09-05 00:44  Dylan_Java_NYC  阅读(193)  评论(0编辑  收藏  举报