题解 | #二叉搜索树的第k个节点#

二叉搜索树的第k个节点

http://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff

由于是二叉搜索树,采用中序遍历得到的第k个节点即第k小的值,判断输出是否是第k个就可以返回值了,使用来辅助遍历


/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param proot TreeNode类 
     * @param k int整型 
     * @return int整型
     */
    public int KthNode (TreeNode proot, int k) {
        if(proot == null)    return -1;
        //中序遍历,第k个节点
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(proot);
        TreeNode node = proot;
        int i = 0;
        while(!stack.isEmpty()){
            //遍历node下的所有左节点
            while(node.left != null){
                stack.push(node.left);
                node = node.left;
            }
            i++;
            if(i == k)    return stack.pop().val;
            TreeNode tmp = stack.pop();
            //加入右子树
            if(tmp.right != null){
                stack.push(tmp.right);
                node = tmp.right;
            }
        }
        return -1;
    }
}

也可以使用递归的方法


/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param proot TreeNode类 
     * @param k int整型 
     * @return int整型
     */
    int count = 0;    //标记遍历的节点数
    int result = -1;
    public int KthNode (TreeNode proot, int k) {
        if(proot == null || k <= 0)    return -1;
        KthNode(proot.left,k);
        ++count;
        if(count == k)    return result = proot.val;
        KthNode(proot.right,k);
        return result;
    }
}
全部评论
你遍历的方法不对,遍历到叶子节点时,其左孩子是null,执行if语句,直接return -1咯
1 回复 分享
发布于 2021-12-29 12:41
请问非递归的方法第36行,为什么要新建一个tmp变量,直接用node不行嘛
点赞 回复 分享
发布于 2022-03-25 11:10
这是C++写的吗
点赞 回复 分享
发布于 2022-04-01 11:27

相关推荐

01-07 15:50
四川大学 Java
看日出看日落:好好背八股,做算法。我身边跟你bg差不多的基本都大厂暑期
点赞 评论 收藏
分享
评论
9
1
分享

创作者周榜

更多
牛客网
牛客企业服务