Skip to content

Instantly share code, notes, and snippets.

@jason51122
Created July 29, 2014 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jason51122/65eb1683389527029069 to your computer and use it in GitHub Desktop.
Save jason51122/65eb1683389527029069 to your computer and use it in GitHub Desktop.
4.4 Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D,you'll have D linked lists).
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
TreeNode[] pre = new TreeNode[1];
pre[0] = null;
return helper(root, pre);
}
private boolean helper(TreeNode root, TreeNode[] pre) {
if (root == null) {
return true;
}
if (!helper(root.left, pre)) {
return false;
}
if (pre[0] != null && pre[0].val >= root.val) {
return false;
}
pre[0] = root;
if (!helper(root.right, pre)) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment