题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。
示例1
输入
{5,3,7,2,4,6,8},3
返回值
{4}
解题思路
根据二叉搜索树的概念,一路向左,最左下是最小的,之后是右子树。然后递归到上一层
完全遍历完左子树之后,再去右子树
示例中{5,3,7,2,4,6,8}的树形结构为
----5
-- 3---7
-2 4 6 8
java代码实现
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int count=0;//记录第几小,全局变量,在递归时累加
TreeNode ans=null;//记录结果
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null) return ans;
KthNode(pRoot.left,k);//一直递归找左子树,只有左子树为空,才会跳出
count++;
if(count==k){//跳出时,左子树为空,则证明根节点是当前的第几小节点
ans=pRoot;
}
if(count>k)
return ans;
else{
KthNode(pRoot.right,k);//递归右子树也是先一路向左,最后左没有了就是第几小元素
}
return ans;
}
}
京公网安备 11010502036488号