题目
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路
该题已经告诉你是二叉搜索树。那么我们直接对其进行中序遍历即可。利用回溯的原理,先到底再从下往上,数第K个结点即可。
AC代码
import java.util.Stack;
/*
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;
int count = 0;
Stack<TreeNode> st = new Stack();
while(pRoot != null || !st.isEmpty()){
while(pRoot != null){
st.push(pRoot);
pRoot = pRoot.left;
}
pRoot = st.pop();
count++;
if(count == k)
return pRoot;
pRoot = pRoot.right;
}
return null;
}
}
本文介绍了一种在二叉搜索树中寻找第K小结点的算法,通过中序遍历的方式,利用回溯原理,从根节点开始向下遍历到最左子节点,然后依次向上返回并计数,直到找到第K个结点。
172万+

被折叠的 条评论
为什么被折叠?



