-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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