力扣174. 寻找二叉搜索树中的目标节点(java,二叉搜索树的性质的运用)

Problem: LCR 174. 寻找二叉搜索树中的目标节点

文章目录

思路

首先我们可以知道二叉搜索树的如下性质

1.若中序遍历先遍历左子树再右子树可以的到一个递增的序列

2.若中序遍历先遍历右子树再左子树可以的到一个递减的序列

所以我们得出如下思路:

1.以右-根-左 的顺序中序递归遍历

2.在递归遍历的归的过程中记录一个递增变量,当其为第cnt大的时,结束递归返回该节点值即可。

解题方法即注意点

大体解题方法见思路,注意下点可以优化代码

当记录的递增变量大于等于cnt时,即可退出递归达到一个减枝的效果

复杂度

  • 时间复杂度:

O ( n ) O(n) O(n)

  • 空间复杂度:

O ( n ) O(n) O(n)

Code

java 复制代码
/**
 * 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 {
    //Time Complexity: O(n)
    //Space Complexity: O(n)

    int count = 0;
    int result;
    public int findTargetNode(TreeNode root, int cnt) {
        inorder(root,cnt);
        return result;
    }

    //二叉搜索树的中序遍历函数
    //左根右:从小到大
    //右根左:从大到小
    public void inorder(TreeNode root, int cnt) {
        //减枝:当count大于cnt时直接退出
        if (count >= cnt) return;
        if (root == null) return;
        //先遍历右子树
        inorder(root.right,cnt);
        count++;
        //再归的过程中查找是否存在
        if (count == cnt) {
            result = root.val;
            return;
        }
        inorder(root.left,cnt);
    }

}
相关推荐
老师我太想进步了202630 分钟前
【数据结构-8】栈的实现
c语言·数据结构·算法
装不满的克莱因瓶1 小时前
【从零搭建】AI大模型之ReactAgent智能体对接MCP实战
java·人工智能·ai·springai·mcp·springaialibaba
kyle~1 小时前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
SimonKing2 小时前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
Resean02232 小时前
SpringMVC 6+源码分析(九)异常处理
java·spring·springmvc
geats人山人海2 小时前
现代c++4.1
java·开发语言·c++
Pniubi3 小时前
贪心算法入门
算法·贪心算法
MobotStone3 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法
下一站春风里3 小时前
Spring IoC 控制反转 完整技术笔记
java·spring boot·笔记·spring
挖掘狂人3 小时前
用户连点两次「确认支付」,你的后端凭什么只扣一次钱?
java·后端·面试