首页 > 其他 > 详细

Leetcode & CTCI ---Day 2

时间:2015-07-11 22:49:40      阅读:341      评论:0      收藏:0      [点我收藏+]

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.

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null)
            return true;
        if (getHeight(root) != -1)
            return true;
        return false;
    }
    
    public int getHeight(TreeNode root){
        if (root == null)
            return 0;
        int left_height = getHeight(root.left);
        int right_height = getHeight(root.right);
        if (left_height == -1 || right_height == -1)
            return -1;
        if (Math.abs(left_height - right_height) > 1)
            return -1;
        return Math.max(left_height, right_height) + 1;
    }
}

Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   /   2   2
 / \ / 3  4 4  3

 

But the following is not:

    1
   /   2   2
   \      3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

I did not figure how to do this fisrtly. Then I read some solution and figure it as recursive solution. I did not think about iterative solution this time. 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null)
            return true;
        return isSymmetric(root.left, root.right);
    }
    
    public boolean isSymmetric(TreeNode left, TreeNode right){
        if (left == null && right == null)
            return true;
        else if (left == null || right == null)
            return false;
        else if (left.val != right.val) return false;
        else if (!isSymmetric(left.left, right.right)) return false;
        else if (!isSymmetric(left.right, right.left)) return false;
        return true;
    }
}

 

 

 

 

Leetcode & CTCI ---Day 2

原文:http://www.cnblogs.com/timoBlog/p/4639436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!