https://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
【题目】
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
【代码】
//想的笨方法,先递归中序遍历到list,再取元素
TreeNode KthNode(TreeNode root, int k)
{
if(root==null||k<=0) return null;
ArrayList<TreeNode> list=new ArrayList<TreeNode>();
core(root,list);
if(k>list.size()) return null;
return list.get(k-1);
}
public void core(TreeNode root,ArrayList<TreeNode> list){
if(root.left!=null) core(root.left,list);
list.add(root);
if(root.right!=null) core(root.right,list);
}
//节省一点空间
public class Solution {
int index = 0; //计数器
TreeNode KthNode(TreeNode root, int k)
{
if(root != null){ //中序遍历寻找第k个
TreeNode node = KthNode(root.left,k);
if(node != null)
return node;
index ++;
if(index == k)
//此时找到对应节点,但是递归并没有结束,所以需要将结果逐层返回
return root;
node = KthNode(root.right,k);
if(node != null)
return node;
}
return null;
}
}
【理解】
作者:╰╰风丶继续吹
链接:https://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
来源:牛客网
如果没有if(node != null)这句话 那么那个root就是返回给上一级的父结点的,而不是递归结束的条件了,有了这句话过后,一旦返回了root,那么node就不会为空了,就一直一层层的递归出去到结束了。举第一个例子{8,6,5,7,},1 答案应该是5,如果不加的时候,开始,root=8,node=kth(6,1),继续root=6,node=kth(5,1)root =5 返回null,这时向下执行index=k=1了,返回 5给root=6递归的时候的node,这时回到root=8了,往后面调右孩子的时候为空而把5给覆盖了。现在就为空了,有了这句话后虽然为空,但不把null返回,而是继续返回5
本文介绍了一种在二叉搜索树中查找第K大结点的方法。通过中序遍历的方式,利用递归实现了两种算法:一种是将遍历到的所有结点存入列表再获取目标结点;另一种是在遍历过程中直接判断并返回第K大结点。
180

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



