94. Binary Tree Inorder Traversal && 230. Kth Smallest Element in a BST

 

 

public List<Integer> inorderTraversal(TreeNode root) {
        Deque<TreeNode> nodes = new ArrayDeque<TreeNode>();
        List<Integer> visits = new LinkedList<Integer>();
        TreeNode next = root;
        while(!nodes.isEmpty() || next != null)
        {
            if(next != null)
            {
                nodes.push(next);
                next = next.left;
            }
            else
            {
                TreeNode processing = nodes.pop();
                visits.add(processing.val);
                next = processing.right;
            }
            
        }
        return visits;
    }

 

 

 

230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> nodes = new ArrayDeque<TreeNode>();
        TreeNode next = root;
        while(!nodes.isEmpty() || next != null)
        {
            if(next != null)
            {
                nodes.push(next);
                next = next.left;
            }
            else
            {
                TreeNode processing = nodes.pop();
                //visit processing.
                if(k == 1)
                    return processing.val;
                --k;
                next = processing.right;
            }
            
        }
        return Integer.MAX_VALUE;
    }
}

 

 

posted @ 2015-09-25 12:08  新一代的天皇巨星  阅读(166)  评论(0)    收藏  举报