本文主要是介绍leetcode oj java 98. Validate Binary Search Tree,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、问题描述:
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.
Example 1:
2/ \1 3Binary tree
[2,1,3]
, return true.
Example 2:
1/ \2 3Binary tree
[1,2,3]
, return false.
二、解决思路:
二分搜索树的中序遍历应该是一个有序的数组,把树中序遍历判断数组是否有序
三、代码:
package T12;import java.util.ArrayList;
import java.util.List;/*** @author 作者 : xcy* @version 创建时间:2016年12月30日 下午1:58:43* 类说明*/
public class t98 {public static void main(String[] args) {// TODO Auto-generated method stubTreeNode root = new TreeNode(10);TreeNode r1 = new TreeNode(6);TreeNode r2 = new TreeNode(14);TreeNode r3 = new TreeNode(4);TreeNode r4 = new TreeNode(8);TreeNode r5 = new TreeNode(12);TreeNode r6 = new TreeNode(16);root.left = r1;root.right = r2;r1.left = r3;r1.right = r4;r2.left = r5;r2.right = r6;System.out.println(isValidBST(root));}public static boolean isValidBST(TreeNode root) {if (root == null || (root.left == null && root.right == null)) {return true;}List<Integer> list = new ArrayList<Integer>();genList(root, list);for (int i = 0; i < list.size() - 1; i++) {if (list.get(i) > list.get(i + 1))return false;}return true;}public static void genList(TreeNode root, List<Integer> list) {if (root == null) {return;}genList(root.left, list);list.add(root.val);genList(root.right, list);}}
这篇关于leetcode oj java 98. Validate Binary Search Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!