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

    }


}

记录

总结

相关推荐
atunet28 分钟前
关于图算法中的连通分量检测与最小割问题7
算法
心运软件1 小时前
银行客户流失预测(Python 完整实战)
算法
邪神与厨二病1 小时前
牛客周赛 Round 153
python·算法
qizayaoshuap3 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语4 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet4 小时前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_4 小时前
rog_map参数理解
算法
春日见4 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表
叩码以求索5 小时前
统计按位或能得到最大值的子集数目(一)
数据结构·算法
tachibana25 小时前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode