Kth Smallest Element in a BST

题目链接:https://leetcode.com/problems...

inorder traverse:

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        // morris: inorder traverse
        TreeNode cur = root, prev = null;
        int count = 0;
        while(cur != null) {
            // reach the end of left part
            if(cur.left == null) {
                if(++count == k) return cur.val;
                cur = cur.right;
            }
            else {
                prev = cur.left;
                // find the right most part
                while(prev.right != null && prev.right != cur) prev = prev.right;
                // reach the end of current right part
                if(prev.right == null) {
                    prev.right = cur;
                    cur = cur.left;
                }
                // recover the tree
                else {
                    prev.right = null;
                    if(++count == k) return cur.val;
                    cur = cur.right;
                }
            }
        }
        
        return -1;
    }
}

二分找结果,按左边nodes数来分:

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int left = getNum(root.left);
        if(left == k - 1) return root.val;
        else if(left < k - 1) return kthSmallest(root.right, k - left - 1);
        else return kthSmallest(root.left, k);
    }
    
    private int getNum(TreeNode node) {
        if(node == null)  return 0;
        // divide and conquer
        return 1 + getNum(node.left) + getNum(node.right);
    }
}

如果改下node,加入number of left的field,那就可以在O(h)时间内找到结果了:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     int leftNum;
 *     TreeNode(int x, int num) { val = x; leftNum = num; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int left = root.leftNum;
        if(left == k - 1) return root.val;
        else if(left < k - 1) return kthSmallest(root.right, k - left - 1);
        else return kthSmallest(root.left, k);
    }
}

lulouch13
13 声望6 粉丝