题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。
例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
分析
二叉搜索树的中序遍历结果就是从小到大的排序,找到第k个即可。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.*; public class Solution { TreeNode KthNode(TreeNode pRoot, int k){ ArrayList<TreeNode> list = new ArrayList<>(); if(pRoot==null || k<=0) return null; Stack<TreeNode> stack = new Stack<>(); while(!stack.isEmpty() || pRoot!=null){ if(pRoot!=null){ stack.push(pRoot); pRoot = pRoot.left; }else{ pRoot=stack.pop(); list.add(pRoot); pRoot = pRoot.right; } } if(k>list.size()) return null; return list.get(k-1); } }
方法二:使用计数器
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import java.util.*; public class Solution { TreeNode KthNode(TreeNode pRoot, int k){ if(pRoot==null || k<=0) return null; Stack<TreeNode> stack = new Stack<>(); int count = 0; while(!stack.isEmpty() || pRoot!=null){ if(pRoot!=null){ stack.push(pRoot); pRoot = pRoot.left; }else{ pRoot=stack.pop(); count++; if(count==k) return pRoot; pRoot = pRoot.right; } } return null; } }
最后
以上就是爱笑电灯胆最近收集整理的关于剑指Offer:二叉搜索树的第k个结点(java版)的全部内容,更多相关剑指Offer:二叉搜索树内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复