美文网首页
Binary Search Tree

Binary Search Tree

作者: MisAutumn | 来源:发表于2018-06-08 17:37 被阅读10次

二叉搜索树的特点:
左子树所有节点都比node小,右子树所有节点都比node大
中序遍历为递增序列。

230. Kth Smallest Element in a BST

疑问:为什么定义全局变量时加上static就出错,不加就通过了?

class Solution {
    private int count = 0;
    private int result = 0;
    public int kthSmallest(TreeNode root, int k) {
        inorderTreverse(root, k);
        return result;
    }
    public void inorderTreverse(TreeNode root, int k){
        if(root==null) return;
        System.out.println(result);
        inorderTreverse(root.left, k);
        count++;
        if(count==k) {
            result = root.val;
            return;
        }
        inorderTreverse(root.right, k);
    }
}

98. Validate Binary Search Tree

思路:
利用BST的第一条性质解题:每递归一个节点,还要递归该节点的所有子节点。时间复杂度O(n^2)。
利用第二条性质解题:中序遍历,只用递归一次,时间复杂度变为O(n)。

class Solution {
    private TreeNode pre;
    public boolean isValidBST(TreeNode root) {
        if(root==null) return true;
        pre = null;
        return inOrder(root);
    }
    
    public boolean inOrder(TreeNode root){
        if(root==null) return true;
        if(!inOrder(root.left)) return false;
        if(pre!=null && root.val<=pre.val) return false;
        pre=root;
        return inOrder(root.right);
    }
}

参考: http://zxi.mytechroad.com/blog/tree/leetcode-98-validate-binary-search-tree/

相关文章

网友评论

      本文标题:Binary Search Tree

      本文链接:https://www.haomeiwen.com/subject/wieasftx.html