Jan 27 - Valid Binary Search Tree; DFS;
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jan 27 - Valid Binary Search Tree; DFS;相关的知识,希望对你有一定的参考价值。
Using DFS to traverse the BST, when we look through the BST to a certain node, this node must have the following property to make sure the tree is a valid BST:
if current node is a left child of its parent, its value should smaller than its parent‘s value.
then its left child(if exists,), its value should smaller than its own. While its right child, if exists, the value should should be larger than current node‘s but smaller than the parent‘s
Similarly, we can find the property of a node which is a right child of its parent.
We use two long-type variable to record the MIN, MAX value in the remaining tree. When we goes into a left child of current, update the max to be current node‘s value, when we goes into a right child of current node, update the min to be current node‘s value. Basically the min and max value is related to the parent node‘s value. Initially we set Min to be Integer.MIN_VALUE-1 and MAX to be Integer.MAX_VALUE +1, to make sure it works when we look into root‘s child nodes, here Using long data type to avoid over range of integer value.
Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { if(root == null) return true; long min = (long) (Integer.MIN_VALUE)-1; long max = (long) (Integer.MAX_VALUE)+1; return isValidLeftSubtree(root.left, root.val, min) && isValidRightSubtree(root.right, max, root.val); } public boolean isValidLeftSubtree(TreeNode node, long max, long min){ if(node == null) return true; if(node.val >= max || node.val <= min) return false; return isValidLeftSubtree(node.left, node.val, min) && isValidRightSubtree(node.right, max, node.val); } public boolean isValidRightSubtree(TreeNode node, long max, long min){ if(node == null) return true; if(node.val >= max || node.val <= min) return false; return isValidLeftSubtree(node.left, node.val, min) && isValidRightSubtree(node.right, max, node.val); } }
以上是关于Jan 27 - Valid Binary Search Tree; DFS;的主要内容,如果未能解决你的问题,请参考以下文章
convert-sorted-list-to-binary-search-tree
Jan 29 - Flatten Binary Tree To Linked List; DFS;
LeetCode 98: Valid Binary Search Tree
Jan 23 - Search In Rotated Array II; Array; Binary Search;
Jan 26 - Unique Binary Search Trees; DP; Trees; Recursion & Iteration;
Jan 28 - Construct Binary Tree From Preorder And Inorder; Tree; DFS; Array