首页 > 其他 > 详细

剑指offer:二叉搜索树的第k个结点(中序遍历)

时间:2019-09-15 10:28:56      阅读:113      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

剑指offer:二叉搜索树的第k个结点(中序遍历)

原文:https://www.cnblogs.com/haimishasha/p/11520907.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!