首页 > 其他 > 详细

LeetCode230. 二叉搜索树中第K小的元素

时间:2020-12-26 11:44:28      阅读:29      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

思路:中序遍历 递归 / 非递归

 

class Solution {
    int count = 0;
    int res = 0;
    public int kthSmallest(TreeNode root, int k) {
        inOrder(root, k);
        return res;
    }
    private void inOrder(TreeNode root, int k) {
        if (root == null) return;
        inOrder(root.left, k);
        count ++;
        if (count == k) {
            res = root.val;
            return;
        }
        inOrder(root.right, k);
    }
}

 

class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (-- k == 0) {
                return root.val;
            }
            root = root.right;
        }
        return -1;
    }
}

 

LeetCode230. 二叉搜索树中第K小的元素

原文:https://www.cnblogs.com/HuangYJ/p/14189507.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!