64. K-node binary search tree

Subject 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.

Analysis of ideas:

  According to the particularity of binary search tree, we preorder sequence is an ordered sequence it generates, so in order to traverse the first point is the first K K small nodes.

Code:

import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
    /*
    用非递归的方式实现中序遍历
    */
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null||k<0)
            return null;
        TreeNode pNode=pRoot;
        Stack<TreeNode>s=new Stack<>();
        int count=0;
        while(pNode!=null||!s.isEmpty()){
            while(pNode!=null){
                s.push(pNode);
                pNode=pNode.left;
            }
            if(!s.isEmpty()){
                pNode=s.pop();
                count++;
                if(count==k)
                    return pNode;
                pNode=pNode.right;
            }
        }
        return null;
    }


}

Guess you like

Origin www.cnblogs.com/yjxyy/p/10962599.html