您的位置:首页 > 其它

leetcode之Maximum Depth of Binary Tree 以及Balanced Binary Tree

2015-06-12 21:59 435 查看
Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

二叉树的深度,用递归特别方便!

代码如下:

public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int le = maxDepth(root.left);
int ri = maxDepth(root.right);
return le > ri ? (le+1) : (ri+1);
}


  扩展:判断一棵树是不是平衡二叉树?

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.

可以使用一般的方法,对每个结点求出左右深度,然后深度相减,绝对值是否小于1,但是这样会可能重复遍历一个节点多次。

代码一:虽然有重复计算,但是最终返回值那里很精妙。

    public boolean isBalanced(TreeNode root) {

return maxDepth1(root) != -1;
}

private static int maxDepth1(TreeNode root) {
if (root == null) {
return 0;
}

int left = maxDepth1(root.left);
int right = maxDepth1(root.right);
if (left == -1 || right == -1 || Math.abs(left-right) > 1) {
return -1;
}
return Math.max(left, right) + 1;

}


  代码2:利用了TreeNode结构中的val,用它来记录以当前结点为根的子树的高度,避免多次计算。

  public boolean isBalanced(TreeNode root) {
height(root);
return run(root);
}

public boolean run(TreeNode root) {
if (root == null) return true;

int l = 0, r = 0;
if (root.left != null) l = root.left.val;
if (root.right != null) r = root.right.val;
if (Math.abs(l - r) <= 1 && isBalanced(root.left) && isBalanced(root.right)) return true;

return false;
}

public int height(TreeNode root) {
if (root == null) return 0;
root.val = Math.max( height(root.left), height(root.right) ) + 1;
return root.val;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: