点击上方"蓝字",关注了解更多
又是一年秋招季
后台回复【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)
如果您觉得本文有用,请点个“赞”
你点的每一个在看,我都认真当成了喜欢