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

    }


}

记录

总结

相关推荐
江畔柳前堤2 分钟前
Function Calling 与 Tool Calling:从认知到工程的全景深度解析
开发语言·网络·人工智能·深度学习·算法·机器学习·php
Navigator_Z4 分钟前
LeetCode //C - 1192. Critical Connections in a Network
c语言·算法·leetcode
zander25829 分钟前
LeetCode 739:每日温度——为什么单调栈要持续弹出
开发语言·python·算法
2601_9557598831 分钟前
如何降低 Claude API 批量生产返工率
大数据·人工智能·算法
rannn_11140 分钟前
【力扣hot100】链表专题下|138、148、23、146
java·算法·leetcode·链表·开发
ly768944 分钟前
分布式一致性算法详解:从 2PC、3PC 到 Paxos、Raft、ZAB
分布式·算法
阿维的博客日记1 小时前
保姆级教程-BBPE分词算法
算法·bbpe
不会就选b2 小时前
算法日常・每日刷题--<优先级队列>2
数据结构·算法
hanlin032 小时前
刷题笔记:力扣第189题-轮转数组
笔记·算法·leetcode
琥珀色糖2 小时前
leetcode hot100题(持续更新)移动零(双指针)
算法·leetcode·职场和发展·双指针·移动零