zoukankan      html  css  js  c++  java
  • 剑指offer:二叉搜索树的第k个结点(中序遍历)

    1. 题目描述

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

    2. 思路

    中序遍历二叉搜索树,第K个就是结果

    3. 非递归

    import java.util.*;
    
    public class Solution {
        static TreeNode KthNode(TreeNode pRoot, int k){
            return inorderNR(pRoot, k);
        }
    
        public static TreeNode inorderNR(TreeNode pRoot, int k){
            int count = 0;
            Stack<TreeNode> s = new Stack<>();
            TreeNode curr = pRoot;
            while(curr != null || !s.empty()){
                while(curr != null){
                    s.push(curr);
                    curr = curr.left;
                }
                curr = s.pop();
                count++;
                if(count == k){
                    break;
                }
                curr = curr.right;
            }
            return curr;
        }
    }

    4. 递归

    import java.util.*;
    
    public class Solution {
        TreeNode KthNode(TreeNode pRoot, int k){
            return inorderR(pRoot, k);
        }
        public int count = 0;//注意不能是静态
        public TreeNode inorderR(TreeNode root, int k){
            if(root != null){
                //
                TreeNode left = inorderR(root.left, k);
                if(left != null) {return left;}
                //
                count ++;
                if(count == k) {return root;}
                //
                TreeNode right = inorderR(root.right, k);
                if(right != null) {return right;}
            }
            return null;
        }
    }
  • 相关阅读:
    访问修饰符
    SqlServer 查运行进程
    SqlServer 作业计时执行存储过程,杀超时进程
    VS快捷键操作
    sql server 命令
    vs 加载 dev控件
    TreeList显示[+] [-] 线条样式
    佳能MG2580S清零
    Dev WaitDialog 使用
    导出.txt / .pdf / .xls
  • 原文地址:https://www.cnblogs.com/haimishasha/p/11520907.html
Copyright © 2011-2022 走看看