isValidBST & Balanced binary Tree

isValidBST

public boolean isValidBST(TreeNode root) {
return valid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

private boolean valid(TreeNode root, int low, int high) {
if (root ==null) return true;
return root.val > low && root.val < high
&& valid(root.left.val, low, root.val) && valid(root,right, root.val, high);
}

// Correction:

  1. the corner case:
    if root == null
  2. the first param in "valid" should be TreeNode rather than the value

// isValidBST

public boolean isValidBST(TreeNode root) {
return valid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

private boolean valid(TreeNode root, int low, int high) {
if (root ==null) return true;
return root.val > low && root.val < high
&& valid(root.left, low, root.val)
&& valid(root,right, root.val, high);
}

// When the TreeNode contain the infinite, above code won't work;
// so we replace the MAX and MIN with null

private boolean valid(TreeNode root, int low, int high) {
if (root ==null) return true;
return (low == null || root.val > low) && ( high == null || root.val < high)
&& valid(root.left, low, root.val)
&& valid(root,right, root.val, high);
}

// OR we can traverse the Tree using inOrder and check whether the array we obtained is
// monotonically increases.

Balanced binary Tree

// Notice that: by counting the tree balanced or not, we should use the height = MAX depth

public boolean isBalanced(TreeNode root) {
if(root == null) return true;
// if Math.abs(maxDepth(root.left) - maxDepth(root.right) > 1) {return false;}
// return isBalanced(root.left) && isBalanced(root.right);

return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 
&& isBalanced(root.left) 
&& isBalanced(root.right);

}

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

// Above approach recalculates max depth for each node repeatedly,
// we can optimize it by passing the depth bottom up

public boolean isBalanced(TreeNode root) {
return maxDepth(root);
}

public int maxDepth(TreeNode root) {
if (root == null) return 0;
L = maxDepth(root.left);
if (L == -1) return -1;
R = maxDepth(root.rigth);
if (R == -1) return -1;
return (Math.abs(L - R) <= 1) ? (Math.max(L, R) + 1) : -1;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 自己就是一个拖延症患者,而且病的不轻。遇到自己不熟悉的事情,不愿放弃现有的安全感,总是认为自己没有准备好,自己还没...
    小关_dec3阅读 221评论 0 0
  • 各位伙伴们,大家晚上好! 首先感谢独行侠给我这次表现的机会 也谢谢大家愿意把美好的周末晚上跟我一起度过。 我是大家...
    Anky17阅读 327评论 0 0