码迷,mamicode.com
首页 > 其他好文 > 详细

二叉搜索树的第k个结点

时间:2018-10-11 18:57:59      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:empty   new   nbsp   ack   数值   pop   bsp   中序遍历   tac   

题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
此树按照中序遍历打出来是[2 3 4 5 6 7 8],所以第三大的节点是4
Solution 1://借助stack
public class Solution {
    int count = 0;

    TreeNode KthNode(TreeNode pRoot, int k) {

        if(count > k || pRoot == null)

            return null;

        TreeNode p = pRoot;

        Stack<TreeNode> stack = new Stack<>();

        TreeNode kthNode = null;

        stack.push(pRoot);

        while(!stack.isEmpty()){

            TreeNode tn = stack.peek();

            while(tn != null){

                tn = tn.left;

                stack.push(tn);

            }

            stack.pop();

            if (!stack.isEmpty()) {

                tn = stack.pop();

                count++;

                if (count == k)

                    kthNode = tn;

                stack.push(tn.right);

            }

        }

        return kthNode; 

    }  

}
Solution 2:
public class Solution {
    int k;
    TreeNode temp = null;
    public TreeNode KthNode(TreeNode pRoot, int k) {
              this.k = k;
              helper(pRoot);
              return temp;
    }
 
    public void helper(TreeNode pRoot) {
             if (pRoot == null)
                 return;
             helper(pRoot.left);
             if (--k == 0)
                 temp = pRoot;
             helper(pRoot.right);
    }
}

二叉搜索树的第k个结点

标签:empty   new   nbsp   ack   数值   pop   bsp   中序遍历   tac   

原文地址:https://www.cnblogs.com/MarkLeeBYR/p/9773509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!