您的位置:首页 > Web前端

剑指offer——二叉搜索树的第k个结点(一般)

2017-07-06 17:25 435 查看
题目描述

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

思路:

首先根据二叉搜索树的特点,根节点大于其左子树,小于其右子树。因为题目要求求出第k个节点,我们发现中序遍历得到的就是从小到大的顺序。

public class Solution {
int index = 0;
TreeNode result;
boolean found = false;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(k<=0)
return null;
if(pRoot==null||found==true) // 找到后快点跳出
return null;
KthNode(pRoot.left,k);
index++;
if(index==k){
result = pRoot;
found = true;
}
KthNode(pRoot.right,k);
return result;
}
}


非递归:

import java.util.Stack;
public class Solution {
//中序递归
int count = 0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(count > k || pRoot == null)
return null;
TreeNode p = pRoot;
Stack<TreeNode> LDRStack = new Stack<TreeNode>();
TreeNode kthNode = null;
while(p != null || !LDRStack.isEmpty()){
while(p != null){
LDRStack.push(p);
p = p.left;
}
TreeNode node = LDRStack.pop();
System.out.print(node.val+",");
count++;
if(count == k){
kthNode = node;
break;
}
p = node.right;
}
return kthNode;
}
}


更简洁的写法:

import java.util.*;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
int index = 0;
Stack<TreeNode> stack = new Stack<>();
while(pRoot!=null||!stack.isEmpty()){
while(pRoot!=null){
stack.push(pRoot);
pRoot = pRoot.left;
}
index++;
pRoot = stack.pop();
if(index==k)
return pRoot;
pRoot = pRoot.right;
}
return null;
}
}


只定义一个成员变量inde,递归

public class Solution {
int index = 0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(k<=0||pRoot==null)
return null;
TreeNode result = null;
if(result==null&&pRoot.left!=null)
result = KthNode(pRoot.left,k);
index++;
if(index==k){
return pRoot;
}
if(result==null&&pRoot.right!=null)
result = KthNode(pRoot.right,k);
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: