您的位置:首页 > 其它

二叉搜索树的第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;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: