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.
明顯遞歸的題, 那麼如何遞歸呢?
第一個思路是從下往上的:
這個遞歸函數有三個返回值,原型類似下面,返回這個子樹是不是BST,以及返回這個子樹的最大值和最小值。
boolean isValidBST(TreeNode root, Integer[] values)
這種寫法的缺點在於代碼不夠簡潔,要做很多的判斷。
第二個思路可以從top開始限制子樹的value的範圍,原型就簡單的多:
public boolean isValidBST(TreeNode root, int max, int min)
這個子樹的值必須要在max和min之間, 那麼右子樹的值必須要在root.val和max之間,左子樹的值必須要在min和root.val之間。再加上左右子樹都必須是BST的判斷,大概是來行代碼就能搞定。
public class Solution { public boolean isValidBST(TreeNode root) { return isValidBST(root, Integer.MAX_VALUE,Integer.MIN_VALUE); } /** * values[0] max value of this tree * values[1] min value of this tree */ public boolean isValidBST(TreeNode root, int max, int min) { if(root == null){ return true; } if(root.val<max&& root.val>min&& isValidBST(root.left, root.val, min)&& isValidBST(root.right, max, root.val)){ return true; } return false; } }
上面第二種思路 參考了 【水中的魚】 的文章
http://fisherlei.blogspot.com/2013/01/leetcode-validate-binary-search-tree.html
這個作者有很多leetcode的文章寫得都很好