二叉搜索树的第k小节点
2018-03-23 17:08
387 查看
1.书上的代码没看懂,空间复杂度O(n),时间复杂度O(n)
import java.util.ArrayList;
public class Solution {
public TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null || k<=0) return null;
ArrayList<TreeNode> list=new ArrayList<TreeNode>();
helper(pRoot,k,list);
if(list.size()<k) return null;
return list.get(k-1);
}
public void helper(TreeNode pRoot, int k,ArrayList<TreeNode> list){
if(pRoot!=null){
helper(pRoot.left,k,list);
list.add(pRoot);
helper(pRoot.right,k,list);
}
}
}
2.空间复杂度O(1),时间复杂度O(n) 的代码
public class Solution {
private int index=0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot!=null){
TreeNode p=KthNode(pRoot.left, k);
if(p!=null){return p;}
index++;
if(index==k){return pRoot;}
p=KthNode(pRoot.right, k);
if(p!=null){return p;}
}
return null;
}
}
import java.util.ArrayList;
public class Solution {
public TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null || k<=0) return null;
ArrayList<TreeNode> list=new ArrayList<TreeNode>();
helper(pRoot,k,list);
if(list.size()<k) return null;
return list.get(k-1);
}
public void helper(TreeNode pRoot, int k,ArrayList<TreeNode> list){
if(pRoot!=null){
helper(pRoot.left,k,list);
list.add(pRoot);
helper(pRoot.right,k,list);
}
}
}
2.空间复杂度O(1),时间复杂度O(n) 的代码
public class Solution {
private int index=0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot!=null){
TreeNode p=KthNode(pRoot.left, k);
if(p!=null){return p;}
index++;
if(index==k){return pRoot;}
p=KthNode(pRoot.right, k);
if(p!=null){return p;}
}
return null;
}
}
相关文章推荐
- 剑指Offer-54:二叉搜索树的第k大节点
- 二叉搜索树第k大个节点
- 剑指offer(64):二叉搜索树的第k大的节点
- 找出二叉搜索树第k大的节点
- 寻找二叉搜索树的第K小的节点
- 剑指Offer——二叉搜索树中第K大的节点
- 剑指_43_二叉搜索树第k大节点
- 【剑指offer】面试题54:二叉搜索树的第k大节点
- 二叉搜索树的第K大节点
- 二叉搜索树的节点删除
- 二叉搜索树的第K大结点
- Java实现二叉搜索树节点的删除
- 二叉搜索树删除节点
- 二叉搜索树的第K个节点
- 每天一道LeetCode-----寻找二叉搜索树中第k小的元素
- 二叉搜索树中查找与目标数字最接近的节点
- 求二叉搜索树的第k个节点
- 【算法面试题】寻找二叉搜索树中两个节点的最近公共祖先节点(转)
- 剑指offer-二叉搜索树的第K个节点
- 在二叉搜索树里,寻找两个节点 Find a pair with given sum in a Balanced BST