Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
中序遍历结果是按顺序递增的。根据这一点我们只需要中序遍历这棵树,然后保存前驱结点,每次检测是否满足递增关系即可。注意以下代码没用一个变量去保存前驱结点,原因是java没有传引用的概念,如果传入一个变量,它是按值传递的,所以是一个备份的变量,改变它的值并不能影响它在函数外部的值,算是java中的一个小细节。
做一次树的遍历,所以时间复杂度是O(n),空间复杂度是O(logn)。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { ArrayListSolution2: recursionres = new ArrayList (); //store value of last node res.add(null); return helper(root, res); } public boolean helper(TreeNode root, ArrayList res) { if(root == null) return true; boolean left = helper(root.left, res); //in BST, the result of inorder traversal is in ascending order if(res.get(0) != null && res.get(0) >= root.val) return false; res.set(0, root.val); boolean right = helper(root.right, res); return left && right; } }
O(n) runtime, O(logn) stack space – Top-down recursion
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { return helper(root, null, null); } public boolean helper(TreeNode root, Integer min, Integer max) { if(root == null) return true; return (min == null || root.val > min) && (max == null || root.val < max) && helper(root.left, min, root.val) && helper(root.right, root.val, max); } }
No comments:
Post a Comment