class Solution {
public int findTargetNode(TreeNode root, int cnt) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> s = new Stack<>();
TreeNode cur = root;
while(cur!=null||!s.isEmpty()){
while(cur!=null){
s.push(cur);
cur = cur.left;
}
cur = s.pop();
result.add(cur.val);
cur = cur.right;
}
return result.get(result.size()-cnt);
}
}
class Solution {
int k;
int res;
public int findTargetNode(TreeNode root, int cnt) {
k = cnt;
f(root);
return res;
}
public void f(TreeNode root){
if(root == null || k <= 0){
return;
}
// 从大到小,所以先右节点
f(root.right);
k --;
if(k == 0){
res = root.val;
}
f(root.left);
}
}
/**
解题思路:
根据性质,二叉搜索树中序遍历结果为升序数组,遍历顺序调整为right->root->left即为降序
套用中序遍历模版即可
时间复杂度O(N)
空间复杂度O(N)
*/
class Solution {
public int findTargetNode(TreeNode root, int cnt) {
Deque<TreeNode> st = new ArrayDeque<>();
TreeNode p = root;
while (!st.isEmpty() || p != null){
while (p != null){
st.add(p);
p = p.right;
}
TreeNode cur = st.pollLast();
if (cnt == 1){
return cur.val;
}
cnt--;
p = cur.left;
}
return -1;
}
}
共以下 20 个回答
LCR 174. 寻找二叉搜索树中的目标节点
依据中序结果即可求得二叉搜索树的第n大结果
中序遍历
二叉搜索树中序遍历是递增的,先中序遍历再根据K找
解题思路
– 搜索二叉树,左->中->右,升序排列;右->中->左,降序排列;
– 使用递归进行遍历
– 通过全局变量,可以去记录当前已经遍历到的节点个数,一旦达到目标前n大的时候,程序结束
【题解1】
时间复杂度O(N),空间复杂度O(N)。
时间o(n)
空间o(n)
中序遍历,但是没用递归
思路:中序遍历 记录节点
思路:中序遍历,换成右根左的顺序打印。注意可以在记数为0后剪枝
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res, cnt;
}//倒着来就行
public class Solution {
private int result; // 存储目标节点值
private int count; // 记录已访问的节点数
}
在中序遍历的递归版本中进行剪枝
花了4ms的暴力方法,遍历所有节点存入列表然后排序,最后取出。
On On
看了题解的思路写的法二
on on
时间复杂度O(n),空间复杂度O(h)
思路:二叉搜索树的中序遍历结果是升序的,“所求的第
cnt大的节点”可以转换为“中序遍历倒序的第cnt个节点”。而二叉搜索树的中序遍历倒序的递归遍历方式:右-根-左。时间复杂度:O(n)
空间复杂度:O(n)
class Solution {// 右中左
int res = 0, cnt = 0;
public int findTargetNode(TreeNode root, int k) {
dfs(root, k);
return res;
}
}
时间:O(n)
空间:O(n)