码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -- Validate Binary Search Tree

时间:2015-10-17 01:53:09      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:


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.


就是判断一个二叉树是否为搜索二叉树。


搜索二叉树的定义为,左子树的每个节点都小于当前节点;右子树的每个节点都大于当前节点。


思路:中序遍历节点存入数组,再判断数组是否为递增(不包括相等)。


实现代码:


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public bool IsValidBST(TreeNode root) 
    {
        var result = new List<int>();
    	Travel(root, ref result);
    	
    	for(var i = 0;i < result.Count - 1; i++){
    		if(result[i+1] <= result[i]){
    			return false;
    		}
    	}
    	
    	return true;
    }


private void Travel(TreeNode node ,ref List<int> result)
{
	if(node == null){
		return;
	}
	
	Travel(node.left, ref result);
	result.Add(node.val);
	Travel(node.right, ref result);
}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Validate Binary Search Tree

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/49188109

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!