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

剑指OFFER----面试题54. 二叉搜索树的第k大节点

时间:2020-03-10 13:38:43      阅读:38      评论:0      收藏:0      [点我收藏+]

标签:roo   --   面试题   root   二叉搜索树   tree   null   turn   ack   

链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthLargest(TreeNode root, int k) {
        int cnt = 1;
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.empty()) {
            while (root != null) {
                stack.push(root);
                root = root.right;
            }
            TreeNode cur = stack.pop();
            if (cnt == k) return cur.val;
            cnt++;
            root = cur.left;
        }
        return 0;
    }
}

剑指OFFER----面试题54. 二叉搜索树的第k大节点

标签:roo   --   面试题   root   二叉搜索树   tree   null   turn   ack   

原文地址:https://www.cnblogs.com/clown9804/p/12455083.html

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