LeetCode -- Validate Binary Search Tree
来源:互联网 发布:气象数据下载 编辑:程序博客网 时间:2024/04/29 17:12
题目描述:
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.
就是判断一个二叉树是否为搜索二叉树。
搜索二叉树的定义为,左子树的每个节点都小于当前节点;右子树的每个节点都大于当前节点。
思路:中序遍历节点存入数组,再判断数组是否为递增(不包括相等)。
实现代码:
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);}}
1 0
- LeetCode: Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode : Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Validate binary search tree
- [LeetCode]Validate Binary Search Tree
- [Leetcode]Validate Binary Search Tree
- [leetcode]Validate Binary Search Tree
- LeetCode-Validate Binary Search Tree
- [leetcode] Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- Leetcode Validate Binary Search Tree
- LeetCode | Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- Leetcode: Validate Binary Search Tree
- 【Leetcode】Validate Binary Search Tree
- 【leetcode】Validate Binary Search Tree
- 物流表结构
- Parameter System
- IOS正则表达式,很详细,值得一看!
- 两部分代码比较,所带来的问题,下面已解决
- Android四大组件-BroadcastReceiver
- LeetCode -- Validate Binary Search Tree
- 如何实现从一个app跳转到另一个app的某个Activity
- LeetCode -- Best Time to Buy and Sell Stock
- 有关页面编码的控制问题,乱码如何解决
- LeetCode -- Binary Tree Preorder Traversal
- Scala学习笔记26【Set、Map、TreeSet、TreeMap实战】
- LeetCode -- Climbing Stairs
- json格式化
- 浅谈R语言