[offer-62] k-node of binary search tree 20190910/02

Posted by rReLmy on Tue, 01 Oct 2019 14:27:38 +0200

[offer-62] the k-th node of the binary search tree

  • Test point: stack tree
  • Time limit: 1 second
  • Space limitation: 32768K
  • Given a binary search tree, find the smallest k node. For example, (5, 3, 7, 2, 4, 6, 8) the value of the third smallest node in the order of the number of nodes is 4.
Train of thought:

The binary search tree is printed in the order in which it is traversed in the middle order, which is exactly the order in which it is sorted.
So, finding the k-th node in the middle-order traversal order is the result.

Code:
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.Stack;
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        TreeNode root = pRoot;
        
        if (root == null || k == 0) {
            return null;
        }
        
        int count = 0; // Counter
        Stack<TreeNode> stack = new Stack();
        while (root != null || !stack.empty()) {
            // Go to the leftmost node
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            count++;
            if (count == k) {
                return root;
            }
            root = root.right;
        }
        return null;

    }

}
My question:
  1. Go straight to the left-most subtree and start traversing, then pop out the node, which is traversing to the root node. Index++. See if the index is equal to k now. If it is, go back to root directly. If not, traverse the right subtree.
Other ideas 1:

Non-recursive approach

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int index = 0;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if (pRoot == null) {
            return null;
        }
        
        TreeNode l = KthNode(pRoot.left, k);
        if (l != null) {
            return l;
        }
        index++;
        if (index == k) {
            return pRoot;
        }
        TreeNode r = KthNode(pRoot.right, k);
        if (r != null) {
            return r;
        }
        return null;
        
    }


}

Topics: Java