Prove safety offer: a k-th node of the binary search tree (preorder)

1. Title Description

/ * 
    Given a binary search tree, please find the first k smaller nodes therein. 
    For example, (5,3,7,2,4,6,8), the numerical values according to the third junction point is 4 summary. 
* /

2. Ideas

Preorder binary search tree, it is the result of the K

3. Non-recursive

import java.util.*;

public class Solution {
    static TreeNode KthNode(TreeNode pRoot, int k){
        return inorderNR(pRoot, k);
    }

    public static TreeNode inorderNR(TreeNode pRoot, int k){
        int count = 0;
        Stack<TreeNode> s = new Stack<>();
        TreeNode curr = pRoot;
        while(curr != null || !s.empty()){
            while(curr != null){
                s.push(curr);
                curr = curr.left;
            }
            curr = s.pop();
            count++;
            if(count == k){
                break;
            }
            curr = curr.right;
        }
        return curr;
    }
}

4. recursive

import java.util.*;

public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k){
        return inorderR(pRoot, k);
    }
    public int count = 0;//注意不能是静态
    public TreeNode inorderR(TreeNode root, int k){
        if(root != null){
            //
            TreeNode left = inorderR(root.left, k);
            if(left != null) {return left;}
            //
            count ++;
            if(count == k) {return root;}
            //
            TreeNode right = inorderR(root.right, k);
            if(right != null) {return right;}
        }
        return null;
    }
}

 

Guess you like

Origin www.cnblogs.com/haimishasha/p/11520907.html