二叉树的第k个节点

题目:给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / 3 7 / / 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

思路:中序遍历,计数判断k

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

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

    }

}
*/
 TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null||k<=0)
            return null;
        int i=1;
        Stack<TreeNode> stack=new Stack<TreeNode>();
        TreeNode temp=pRoot;
        while(temp!=null||!stack.isEmpty()){
            while(temp!=null){
                stack.push(temp);
                temp=temp.left;
            }
            temp=stack.pop();
            if(i++==k)
                return temp;
            temp=temp.right;
        }
        return null;
    }
   
原文地址:https://www.cnblogs.com/team42/p/6691799.html