【d66】【Java】【力扣】174.寻找二叉搜索树中的目标节点

思路

反着的中序遍历,并计数

代码

复制代码
/**
 * 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 c=0;
    //要找的数字
    int cnt;
    int result;
    boolean enough=false;

    //寻找第cnt大的数
    public int findTargetNode(TreeNode root, int cnt) {
        this.cnt=cnt;
        fMidOrder(root);
        return result;
    }

    /**
     * 反中序遍历,右中左,遍历一次累计一次,当次数等于cnt,result就是这个数,
     * @param root
     * @return
     */
    public void fMidOrder(TreeNode root) {
        //判断是否足够
        if (enough||root==null) {
            return;
        }
        //遍历右边
        if (root.right!= null) {
            fMidOrder(root.right);
        }
        //遍历自己
        c++;
        if (c==cnt ) {
            result=root.val;
            enough=true;
            return;
        }
        //遍历左边
        if (root.left!= null) {
            fMidOrder(root.left);
        }

    }


}

记录

总结

相关推荐
Star在努力29 分钟前
C语言复习八(2025.11.18)
c语言·算法·排序算法
南山安36 分钟前
从反转字符串看透面试官的“内心戏”:你的算法思维到底怎么样?
javascript·算法·面试
雪不下42 分钟前
计算机中的数学:概率(2)
算法
zs宝来了1 小时前
HOT100-二分查找类型题
算法
_w_z_j_1 小时前
数组中的最长连续子序列
数据结构·算法
地平线开发者1 小时前
征程 6E/M 计算平台部署指南
算法·自动驾驶
mit6.8241 小时前
数位dp|组合数学|差分emplace
算法
2301_764441331 小时前
新能源汽车电磁辐射高级预测
python·算法·数学建模·汽车
Keep_Trying_Go1 小时前
论文Leveraging Unlabeled Data for Crowd Counting by Learning to Rank算法详解
人工智能·pytorch·深度学习·算法·人群计数
仟濹2 小时前
【C/C++】经典高精度算法 5道题 加减乘除「复习」
c语言·c++·算法