每日一题 LEETCODE 230. 二叉搜索树中第K小的元素 JAVA

每日一题 LEETCODE 230. 二叉搜索树中第K小的元素 JAVA,第1张

每日一题 LEETCODE 230. 二叉搜索树中第K小的元素 JAVA

说实话忙的不会写代码了,但还是抽空抄一下每日一题

class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Deque stack=new linkedList<>();
        while(root!=null||!stack.isEmpty()){
            while(root!=null){
                stack.push(root);
                root=root.left;//向左,向小的方向遍历
            }
        //跳出循环时root为空
        //上一个节点就是没有左子树结点
            root=stack.pop();
            k--;
            if(k==0){
                return root.val;
            }
            root=root.right;
        }
        return 0;//root.val;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/3980001.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-10-21
下一篇2022-10-21

发表评论

登录后才能评论

评论列表(0条)

    保存