二叉搜索树的第 K 个结点

题目描述:给定一棵二叉搜索树,请找出其中的第 k 小的结点。例如,(5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为 4。

分析:二叉排序树,中序遍历是递增序列

PS:与牛客相同!

代码:

 1 import java.util.Stack;
 2 
 3 public class Solution{
 4     TreeNode KthNode(TreeNode root, int k){
 5         if(root == null || k == 0){
 6             return null;
 7         }
 8         Stack<TreeNode> stack = new Stack<>();
 9         int count = 0;
10         TreeNode cur = root;
11         while(!stack.isEmpty() || cur != null){
12             while(cur != null){
13                 stack.push(cur);
14                 cur = cur.left;
15             }
16             cur = stack.pop();
17             count++;    
18             if(count == k){
19                 return cur;
20             }
21             cur = cur.right;
22         }
23         return null;
24     }
25 }

 

posted on 2020-08-31 09:56  _那些你很冒险的梦  阅读(86)  评论(0)    收藏  举报

导航