JZ62 二叉搜索树的第k个节点

二叉搜索树的第k个结点

http://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a

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

递归迭代都可以。递归21秒,迭代28秒。

先上递归

public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k){
        if(k<=0) return null;
        this.k=k;
        this.count=0;
        inorder(pRoot);
        return ans;
    }
    int k, count; TreeNode ans;
    void inorder(TreeNode root){
        if(root==null||ans!=null) return;
        inorder(root.left);
        count++;
        if(k==count) ans=root;
        inorder(root.right);
    }
}

再上迭代

import java.util.*;
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k){
        if(k<=0) return null;
        TreeNode curr=pRoot;
        Deque<TreeNode> stack=new ArrayDeque<>();
        int count=0;
        while(!stack.isEmpty()||curr!=null){
            while(curr!=null){
                stack.push(curr);
                curr=curr.left;
            }
            curr=stack.pop(); count++;
            if(count==k) return curr;
            curr=curr.right;
        }
        return null;
    }
}
全部评论

相关推荐

昨天 15:48
上海交通大学 C++
今天投了小鹏,收到了AI面,大概会问哪些啊?
期末一定及格:总共4个部分,心理测评、行测、然后就是问岗位、对岗位的理解、过往遇到了哪些难点怎么解决,很简单,没有什么特别专业的问题,都是一些综合素质相关的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务