面試題54:二叉搜索樹的第k大節點
題目要求:
找出二叉搜索樹的第k大節點。例如,在下圖的樹里,第3大節點的值為4,輸入該樹的根節點,3,則輸出4。
5
/ \
3 7
/ \ / \
2 4 6 8
解題思路:
二叉搜索樹的中序遍歷是有序的。可以引入一個計數器,每訪問一個節點,計數器+1,當計數器等于k時,被訪問節點就是該二叉搜索樹的第k大節點。
package chapter6;
import structure.TreeNode;
import java.util.Stack;
/**
* Created with IntelliJ IDEA
* Author: ryder
* Date : 2017/8/15
* Time : 19:17
* Description:二叉搜索樹的第k大節點
**/
public class P269_KthNodeInBST {
public static TreeNode<Integer> kthNode(TreeNode<Integer> root,int k){
//棧頂元素保證一直是cur的父節點
if(root==null || k<0)
return null;
Stack<TreeNode<Integer>> stack = new Stack<>();
TreeNode<Integer> cur = root;
int count = 0;
while (!stack.isEmpty()||cur!=null){
if(cur!=null){
stack.push(cur);
cur = cur.left;
}
else{
cur = stack.pop();
count++;
if(count==k)
return cur;
cur = cur.right;
}
}
return null;
}
public static void main(String[] args){
TreeNode<Integer> root = new TreeNode<>(5);
root.left = new TreeNode<>(3);
root.left.left = new TreeNode<>(2);
root.left.right = new TreeNode<>(4);
root.right = new TreeNode<>(7);
root.right.left = new TreeNode<>(6);
root.right.right = new TreeNode<>(8);
System.out.println(kthNode(root,3).val);//4
System.out.println(kthNode(root,6).val);//7
System.out.println(kthNode(root,8));//null
}
}
運行結果
4
7
null