1. 程式人生 > >二叉搜尋樹的判斷 leetcode原題

二叉搜尋樹的判斷 leetcode原題

二叉查詢樹(Binary Search Tree)

(又:二叉搜尋樹,二叉排序樹)它或者是一棵空樹,或者是具有下列性質的二叉樹(這也是判斷二叉搜尋樹的標準,即條件)

(1) 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 

(2)若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;

(3)它的左、右子樹也分別為二叉排序樹

leetcode題目:

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.

以下程式是判斷一棵樹

判斷過程:

(1)從根節點開始判斷:左右兩個節點的大小是否符合:左節點值<根節點值<右節點值,並依次遍歷判斷整棵樹左子樹所有節點和右子樹所有節點是否滿足二叉搜尋樹性質(1)和(2);

(2)根節點檢測完成後,開始左右子樹的遍歷,判斷它們是不是二叉搜尋樹

class TreeNode {     int val;     TreeNode left;      TreeNode right;      TreeNode(int x) { val = x; }  } public class Solution { public static boolean IsSubtreeLessThan(TreeNode t, int val) { if (t == null) return true; return (t.val < val && IsSubtreeLessThan(t.left, val) && IsSubtreeLessThan(t.right, val));
} public static boolean IsSubtreeMoreThan(TreeNode t, int val) { if (t==null) return true; return (t.val>val && IsSubtreeMoreThan(t.left, val) && IsSubtreeMoreThan(t.right, val)); } public boolean isValidBST(TreeNode root) { if (root == null) return true; return (IsSubtreeLessThan(root.left, root.val) && IsSubtreeMoreThan(root.right, root.val) && isValidBST(root.left) && isValidBST(root.right));//對應上述“”判斷過程“” } }
新增筆記