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

    }


}

记录

总结

相关推荐
小帽子_12338 分钟前
大功率 PCS 双环闭环控制算法原理与实现
算法
buhuizhiyuci1 小时前
【算法篇】位运算 —— 基础篇
java·数据库·算法
Black蜡笔小新1 小时前
算法训练完了怎么上线?DLTM→AIS→EasyGBS三步交付流水线
人工智能·算法
sycmancia2 小时前
Qt——多线程与界面组件的通信
开发语言·qt·算法
想吃火锅10052 小时前
【leetcode】5.最长回文子串js
算法·leetcode·职场和发展
CoderYanger2 小时前
A.每日一题:1967题+1331题
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
Jasmine_llq2 小时前
《P17010 [GESP202606 五级] 排排坐》
算法·贪心算法·数学化简求和式·排序sort 反向迭代器降序·线性遍历累加计算总权重和
va学弟2 小时前
LeetCode 热题 100 题解(1):哈希
python·算法·leetcode·哈希算法
程序员老陆3 小时前
使用Qt+大华设备SDK预览大华摄像机视频
qt·算法·音视频·视频监控
罗超驿3 小时前
9.优先级队列与堆:从底层原理到实战应用的完整指南
数据结构·算法