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

    }


}

记录

总结

相关推荐
其实防守也摸鱼14 小时前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
Nuanyt15 小时前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
w_zero_one18 小时前
递归算法(一)
java·开发语言·算法
风影同志7832419 小时前
20 个比特能装下多少行情?——实测拆解 Kronos 的 K 线分词器
算法
写的都是BUG20 小时前
APK 里的钥匙,一直就放在门口:聊聊加固真正该做什么
前端·算法
地平线开发者20 小时前
CLIP 的零样本分类:一组文本如何变成图像分类器?
算法
京东云开发者21 小时前
从“会生成”到“能生产”:萤火虫 AIGC 平台的 AI Infra 实践
算法·aigc·产品
youshi666821 小时前
PID——算法改进
算法
一只不想敲代码的程序猿1 天前
如何更高效地拆解问题?
算法