剑指Offer——二叉搜索树中第K大的节点
2018-03-07 18:45
423 查看
题目描述:给定一颗二叉树,找出第K大的节点,这个第K大的节点是从小到大的第K个节点,所以也可以说是第K小的节点。对于一颗二叉树来说,其中序遍历就是节点值从小到大的排列,那么我们用一个ArrayList把中序遍历的结果保存下来,找到第K-1个节点就是第K大的节点。因此很容易想到以下的代码:/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.ArrayList;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
//中序遍历的第k-1个节点就是第k大的节点
if(pRoot == null || k<=0)
return null;
ArrayList<TreeNode> aList = new ArrayList();
inOrderRecursive(pRoot,aList);
int len = aList.size();
if(len<k)
return null;
else
return aList.get(k-1);
}
void inOrderRecursive(TreeNode root,ArrayList<TreeNode> al){
if(root == null){
return;
}
inOrderRecursive(root.left,al);
al.add(root);
inOrderRecursive(root.right,al);
}
}当然,也可以边遍历,边返回节点,这样可以提高效率,比如当这颗二叉树很大,但是K很小的时候,就会大大的节约时间。代码实现如下:
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.ArrayList;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
//中序遍历的第k-1个节点就是第k大的节点
if(pRoot == null || k<=0)
return null;
ArrayList<TreeNode> aList = new ArrayList();
inOrderRecursive(pRoot,aList);
int len = aList.size();
if(len<k)
return null;
else
return aList.get(k-1);
}
void inOrderRecursive(TreeNode root,ArrayList<TreeNode> al){
if(root == null){
return;
}
inOrderRecursive(root.left,al);
al.add(root);
inOrderRecursive(root.right,al);
}
}当然,也可以边遍历,边返回节点,这样可以提高效率,比如当这颗二叉树很大,但是K很小的时候,就会大大的节约时间。代码实现如下:
//思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。 // 所以,按照中序遍历顺序找到第k个结点就是结果。 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; } }
相关文章推荐
- 寻找二叉搜索树的第K小的节点
- 《剑指offer》刷题笔记(树):二叉搜索树的第k个结点
- 《剑指offer》给定一颗二叉搜索树,请找出其中的第k大的结点。
- 二叉搜索树的第K大节点
- 【剑指offer】面试题54:二叉搜索树的第k大节点
- 剑指Offer-54:二叉搜索树的第k大节点
- 剑指Offer(54)二叉搜索树的第K大结点
- 剑指offer——二叉搜索树的第k个节点
- 剑指_43_二叉搜索树第k大节点
- 剑指offer(64):二叉搜索树的第k大的节点
- 二叉搜索树的第k小节点
- 二叉搜索树第k大个节点
- 剑指offer面试题63:二叉搜索树的第k个节点 Java实现
- 找出二叉搜索树第k大的节点
- 剑指offer-二叉搜索树的第K个节点
- 剑指offer-面试题15-链表中倒数第k个节点
- (剑指offer)二叉搜索树的后序遍历序列
- (剑指Offer)面试题24:二叉搜索树的后序遍历序列
- (剑指Offer)面试题27:二叉搜索树与双向链表
- 两个链表的第一个公共节点(剑指offer)