算法思想一:递归
解题思路:
主要通过对二叉树进行中序遍历朝招第K个节点
1、创建中序遍历存储数组 res
2、按照中序遍历:左子树-根节点-右子树,并将遍历的节点信息存储到res中
3、遍历结束,直接返回 res[k-1]
图解:
代码展示:
Python版本
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here # 中序遍历存储数组 res = [] # 中序递归函数 self.inorder(pRoot, res) # 特殊情况 if k == 0 or k > len(res): return None return res[k-1] def inorder(self, pRoot, res): # 二叉树为空 if not pRoot: return res # 递归左子树 self.inorder(pRoot.left, res) # 当前节点进入数组 res.append(pRoot) # 递归左子树 self.inorder(pRoot.right, res)
复杂度分析
时间复杂度O(N):N表示二叉树节点数量,递归遍历二叉树时间
空间复杂的O(N):辅助数组存储二叉树结点空间
算法思想二:非递归(栈)
解题思路:
主要通过中序遍历的过程查找第K个节点 1、定义辅助栈 stack,首先将根节点入栈,count为计算节点数量,初始化为0
2、循环:跳出条件 当前节点为空,栈为空
1、依次将当前节点的左子树节点入栈
2、再将栈内元素出栈,count += 1,如果count == k,则直接返回当前节点即可,否则,则将当前节点的右子树节点依次入栈
3、最后返回二叉树的第k个节点
图解:
代码展示:
JAVA版本
import java.util.Stack;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k) {
// 二叉树为空
if (pRoot == null) {
return null;
}
// 计数
int count = 0;
// 定义栈
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode temp = null;
// 循环结束条件
while (!stack.isEmpty() || pRoot!=null) {
while (pRoot != null) {
// 入栈
stack.push(pRoot);
pRoot = pRoot.left;
}
// 出栈
TreeNode node = stack.pop();
// 计数
count++;
// 如果 count == k 说没找到第k个节点
if (count == k) {
temp = node;
}
pRoot = node.right;
}
return temp;
}
} 复杂度分析
时间复杂度O(N):N表示二叉树节点数量,遍历二叉树所有节点时间
空间复杂的O(N):辅助栈最差情况下存储二叉树所有节点



京公网安备 11010502036488号