二叉搜索树的2层结点统计_剑指offer62二叉搜索树的第k 个结点【Java+Python】

点击上方"蓝字",关注了解更多 d4cb9b517a3c67fc2712751b7030492f.png

又是一年秋招季

后台回复【java面试】获取3G面试资料

后台回复【python面试】获取面试资料

1. 题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。

2. 示例

例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

3. 解题思路

思路:二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。

//     所以,按照中序遍历顺序找到第k个结点就是结果。

4. Java实现

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
*/
import java.util.Stack;
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k){
        // 使用非递归中序遍历二叉树
        if (pRoot == null || k <= 0) return null;
        
        Stack stack = new Stack();int count = 0;while (pRoot != null || !stack.isEmpty()){while (pRoot != null){
                stack.push(pRoot); // 将左节点全部放入栈中
                pRoot = pRoot.left;
            }
            pRoot = stack.pop();
            count += 1;  // 统计节点数量if (count == k) return pRoot;
            pRoot = pRoot.right; // 找到右节点
        }return null;
     }
}

5. Python实现

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回对应节点TreeNode
    def __init__(self):
        self.li = []
    
    def KthNode(self, pRoot, k):
        # write code here
        #先中序遍历,然后获取第k个结点
        if not pRoot or k <= 0:
            return None
        
        self.inOrder(pRoot)
        if len(self.li) #还需要判断k值是否是大于数的大小
            return None
        return self.li[k-1]
        
    def inOrder(self, pRoot): #中序遍历并将遍历结果爆出到数组中
        if pRoot is None:
            return 
        self.inOrder(pRoot.left)
        self.li.append(pRoot)
        self.inOrder(pRoot.right)    

如果您觉得本文有用,请点个“赞”

efca19e22f2419bddf2a0fb2802e1ff6.png                      

你点的每一个在看,我都认真当成了喜欢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值