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

    }


}

记录

总结

相关推荐
大熊背10 小时前
树莓派相机自动白平衡详解(二)
算法·白平衡·isppipeline
Scabbards_10 小时前
面试Leetcode - 算法合集
算法·leetcode·面试
chuan.bai10 小时前
Java RAG 实战附录:qwen3 与 bge-m3 模型切换指南
java·人工智能·算法
wuyk55510 小时前
7.AVL 树:第一个自平衡二叉搜索树
开发语言·stm32·单片机·算法
rannn_11110 小时前
【力扣hot100】二叉树专题+总结
java·算法·leetcode·二叉树
啊嘞嘞?10 小时前
力扣(岛屿数量)
算法·leetcode
zander25811 小时前
LeetCode 198. 打家劫舍
算法·leetcode·深度优先
吃着火锅x唱着歌11 小时前
LeetCode 648.单词替换
算法·leetcode·职场和发展
一只积极向上的小咸鱼11 小时前
分词器tokenizer
算法·llm
Elsa️74611 小时前
leetcode 14.最长公共前缀
算法·leetcode·职场和发展