二叉搜索树的第k个节点-Java实现
二叉搜索树的第k个结点
http://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
一. 思路
二叉搜索树的中序遍历就是一个增序排列。因此以中序遍历的思路,先找左子树最小,再找根,再找右子树,直到找到第k节点为止。非递归解法采用一个栈,一个计数器来解决
二. 非递归解法
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if (pRoot == null || k <= 0) {
return null;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode curNode = pRoot;
int count = 1;// 用作判断当前是第几小节点
//while循环里面采用中序遍历
while (!stack.isEmpty() || curNode != null) {
if (curNode != null) {
stack.push(curNode);
curNode = curNode.left;
} else {
curNode = stack.pop();
if (count++ == k) {
return curNode;
}
curNode = curNode.right;
}
}
return null;
}
}