TreeNode KthNode(TreeNode pRoot, int k) {
int count = 0;
if (count >= k || pRoot == null)
return null;
TreeNode p = pRoot;
Stack<TreeNode> nodeStack = new Stack<>();
nodeStack.push(p);
TreeNode kthNode = null;
while (!nodeStack.isEmpty()) {
while (p != null && p.left != null) {
nodeStack.push(p.left);
p = p.left;
}
TreeNode node = nodeStack.pop();
count++;
if (count == k) {
kthNode = node;
return kthNode;
}
p = node.right;
if (p != null) {
nodeStack.push(p);
}
}
return kthNode;
}
二叉搜索树第k个节点
最新推荐文章于 2021-04-04 19:15:13 发布