二叉搜索树的第k个

链接:https://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a?f=discussion
来源:牛客网

import java.util.*;
public class Solution {
    TreeNode KthNode(TreeNode root, int k) {
        if(root == null || k == 0) return null;
        int count = 0;
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || ! stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            count ++;
            if(count == k) return root;
            root = root.right;
        }
        return null;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-30 18:19
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务