剑指offer(六十二)之二叉搜索树的第k个结点

时间:2016-06-12 01:57:23   收藏:0   阅读:136

题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
代码:
<span style="color:#cc33cc;">/*
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)
    {
        if(pRoot==null||k==0)
            return null;
        Stack<TreeNode> s=new Stack<TreeNode>();
        s.push(pRoot);
        int count=0;
        TreeNode resNode=null;
        while(!s.isEmpty()){        
            while(!s.isEmpty()&&s.peek()!=null){
                TreeNode temp=s.peek();
                s.push(temp.left);
            }
            s.pop();
            if(!s.isEmpty()&&s.peek()!=null){
                TreeNode node=s.pop();
                count++;
                if(count==k){
                    resNode=node;
                    break;
                }
                s.push(node.right);
            }                       
        }
        return resNode;    
    }
}</span>


原文:http://blog.csdn.net/baidu_21578557/article/details/51637355

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!