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

二叉搜索树的第k个节点

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

import java.util.*;

/*
 * 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整型
     */
    // //思路1:递归中序遍历
    // //定义全局变量
    // private int count=0;
    // private int result=-1;
    // public int KthNode (TreeNode proot, int k) {
    //     // write code here
    //     if(k==0) return -1;
    //     dfs(proot,k);
    //     return result;
    // }
    // //写一个递归的函数
    // public void dfs(TreeNode root,int k){
    //     if(root==null) return;
    //     dfs(root.left,k);
    //     count++;
    //     if(count==k){
    //         result = root.val;
    //         return;
    //     }
    //     dfs(root.right,k);
    // }

    //思路2:非递归的中序遍历,需要用到栈
    public int KthNode (TreeNode proot, int k) {
        // write code here
        //边界条件判断
        if(proot==null||k==0) return -1;
        int count = 0;
        //定义栈
        Deque<TreeNode> stack = new LinkedList<>();
        //循环条件,当节点没有访问到头,或者访问到头了但是栈中还有元素没有弹出来
        while(proot!=null || !stack.isEmpty()){
            while(proot!=null){
                //当访问的节点还有,就继续访问左子树,并将节点放入栈中————左
                stack.push(proot);
                proot = proot.left;
            }
            //弹出栈顶元素,count++————中
            TreeNode temp = stack.pop();
            count++;
            if(count==k) return temp.val;
            //再访问弹出的栈顶元素的右子树,其实也是一个左中右的遍历过程————右
            proot = temp.right;
        }
        return -1;
    }
}

全部评论

相关推荐

哞客37422655...:这就是真实社会,没有花里胡哨的安慰,让你感受到阶级分明,不浪费彼此时间。虽然露骨但是唉
点赞 评论 收藏
分享
牛至超人:哈工大已经很棒了,不需要加括号了,然后咋没有实习经历呢?火速趁寒假整一段实习,导师不让就狠狠肘击
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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