二叉搜索树的第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;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务