letcode 98. 验证二叉搜索树

版权声明:be the one ~you will be the one~~ https://blog.csdn.net/Hqxcsdn/article/details/88259628

题目

在这里插入图片描述

思路

中序遍历
将节点加入list 或者 数组中 ,如果递增 ,则答案正确

代码实现

import java.util.LinkedList;
import java.util.List;

/**
 * 
 */

/***
 * @author 18071
 * @Date 2019年3月6日 功能:给定一个二叉树,判断其是否是一个有效的二叉搜索树。 左小于根节点小于 右节点
 * 
 ***/
public class test {
	public static void main(String args[]) {
		Solution s = new Solution();
		TreeNode root = new TreeNode(5);
		root.left = new TreeNode(1);
		root.right = new TreeNode(4);
		root.right.left = new TreeNode(3);
		root.right.right = new TreeNode(6);
		
		TreeNode rua =new TreeNode(1);
		rua.left=new TreeNode(1);
        System.out.println(s.isValidBST(rua));
	}
}

class Solution {
	public boolean isValidBST(TreeNode root) {
		
		List list =  new LinkedList();
		 core(root,list);

		for (int i = 0; i < list.size()-1; i++) {
			if((int)list.get(i)>=(int)list.get(i+1))
			{
				return false;
			}

		}
		return true;
		

	}

	public void core(TreeNode root,List list ) {
		

		if (root != null) {
			// 加入左
			if (root.left != null) {
				
				
				core(root.left,list);
			}

			
			list.add(root.val);
			

			if (root.right != null) {
				
				
				core(root.right,list);
			}

		}
		
		

		

	}

}

class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode(int x) {
		val = x;
	}
}

注意:
如何记录中序遍历的节点值

猜你喜欢

转载自blog.csdn.net/Hqxcsdn/article/details/88259628
今日推荐