Using Inorder traversal in BST

Leave a comment

November 6, 2016 by oneOokay

Inorder traversal: Recursive & 分治

可以用Inorder traversal来解决以下这两个问题:

  • Kth Smallest Element in a BST

    • In-order Iterative
    • In-order Recursive
    • DFS
  • Validate Binary Search Tree

 

Iterative:

 public int kthSmallest(TreeNode root, int k) {
 Stack<TreeNode> stack = new Stack<>();
 int count = 0;
 while(root != null || !stack.isEmpty()){
 while (root != null){
 stack.push(root);
 root = root.left;
 }
 root = stack.pop();
 count ++; //这里也可以用k--,判断k是否为0来代替count
 if (count == k) break;
 root = root.right;
 }
 return root.val;
 }

In-order Recursive:

 

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.

BST左右儿子可以空缺

    public boolean isValidBST(TreeNode root) {
        if (root == null){
            return true;
        }
        Stack stack = new Stack();
        TreeNode pre = null;
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            
            root = stack.pop();
            if (pre != null && pre.val >= root.val){
                return false;
            }
            pre = root;
            root = root.right;
        }
        return true;
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: