給定一個二叉樹,判斷其是否是一個有效的二叉搜索樹。
一個二叉搜索樹具有如下特征:
- 節點的左子樹只包含小於當前節點的數。
- 節點的右子樹只包含大於當前節點的數。
- 所有左子樹和右子樹自身必須也是二叉搜索樹。
示例 1:
輸入: 2 / \ 1 3 輸出: true
示例 2:
輸入: 5 / \ 1 4 / \ 3 6 輸出: false 解釋: 輸入為: [5,1,4,null,null,3,6]。 根節點的值為 5 ,但是其右子節點值為 4 。
解題思路:
由二叉搜索樹的特點可知,若對其進行中序遍歷,得到的則是一個遞增序列。
故采用中序遍歷驗證二叉搜索樹的有效性。
即將每一個節點的值與其上一個節點的值相比較,若大於繼續進行直到遍歷整個二叉樹,若小於則不是有效的二叉樹。
實現代碼:
// 記錄比較結果 private static boolean res = true; // 記錄上個節點的值 private static long max = Long.MIN_VALUE; private static void test(TreeNode root) { if (!res || root == null) return; test(root.left); if (root.val > max) max = root.val; else { res = false; return;} test(root.right); } public static boolean isValidBST(TreeNode root) { if (root == null) return true; test(root); return res; }
對於遞歸函數中所有函數都使用到的變量要設為類變量或實例變量,不能是遞歸函數的局部變量。
如代碼中的 變量res與max。
如下代碼則會出現錯誤:
private static void test(TreeNode root, boolean res, int max) { if (!res || root == null) return; test(root.left, res, max); if (root.val > max) max = root.val; else { res = false; return;} test(root.right, res, max); }
每次遞歸調用的並不是同一個res與max,只是將二者的值傳入調用函數。