Sword refers to offer-54. The kth node of the binary search tree-analysis and code [Java]
1. Title
Given a binary search tree, find the kth smallest node in it. For example, in (5,3,7,2,4,6,8), the value of the third small node is 4 in order of the value of the node.
Two, analysis and code
1. In-order traversal
(1) Thinking
Combining the characteristics of the binary search tree, the sequence obtained by the order traversal is the order sequence of the node values from small to large, so the kth node is the kth node reached by the middle order traversal.
(2) Code
import java.util.Stack;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot == null || k == 0)
return null;
Stack<TreeNode> sta = new Stack<>();
int index = 0;
sta.push(pRoot);
TreeNode node = pRoot;
while (!sta.empty() && index < k) {
while (sta.peek().left != null)
sta.push(sta.peek().left);
while (!sta.empty() && sta.peek().right == null && index < k) {
node = sta.pop();
index++;
}
if (!sta.empty() && index < k) {
node = sta.pop();
index++;
sta.push(node.right);
}
}
if (sta.empty() && index < k)
return null;
return node;
}
}
(3) Results
Running time: 23ms, occupied memory: 9672k.
Three, other
Nothing.