【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);
        }

    }


}

记录

总结

相关推荐
wadesir9 分钟前
Java实现遗传算法(从零开始掌握智能优化算法)
java·开发语言·算法
Jeremy爱编码12 分钟前
leetcode热题腐烂的橘子
算法·leetcode·职场和发展
H CHY24 分钟前
C++代码
c语言·开发语言·数据结构·c++·算法·青少年编程
alphaTao26 分钟前
LeetCode 每日一题 2025/12/22-2025/12/28
算法·leetcode
xiaolang_8616_wjl28 分钟前
c++题目_传桶(改编于atcoder(题目:Heavy Buckets))
数据结构·c++·算法
中國龍在廣州37 分钟前
生成不遗忘,「超长时序」世界模型,北大EgoLCD长短时记忆加持
人工智能·深度学习·算法·自然语言处理·chatgpt
亓才孓42 分钟前
java中的Math.Radom拓展
开发语言·python·算法
霍田煜熙1 小时前
CBMS最新源码
算法
NAGNIP1 小时前
主流的激活函数有哪些?
算法
NAGNIP1 小时前
Self-Attention 为什么要做 QKV 的线性变换?又为什么要做 Softmax?
算法