有效二叉查找树判断(java实现)
生活随笔
收集整理的這篇文章主要介紹了
有效二叉查找树判断(java实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
leetcode 原題 :(即判斷二叉樹是否為二叉查找樹)
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
下面采用java實現:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class ValidateBST{
boolean flag=true;
TreeNode pre=null;//保存前驅節點
public boolean isValidBST(TreeNode root) {
dfs(root);
return flag;
}
//采用中序遍歷,如果前節點不小于當前節點的值,則不符合BST的條件
private void dfs(TreeNode root){
if(root!=null){
dfs(root.left);
if(pre!=null&&root.val<=pre.val)flag= false;
pre=root;
dfs(root.right);
}
}
}
總結
以上是生活随笔為你收集整理的有效二叉查找树判断(java实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html中的字幕滚动marquee属性
- 下一篇: 设计模式之GOF23享元模式