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

    }


}

记录

总结

相关推荐
liliangcsdn24 分钟前
因子分析指标概念与示例
算法·机器学习
SupL!1 小时前
LoftQ原理
算法
Navigator_Z3 小时前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟3 小时前
力扣100——双指针
算法·leetcode
明志数科4 小时前
具身智能真机采集工程实践:5类高频失效模式与规避清单
人工智能·算法·机器学习
CSDN_RTKLIB4 小时前
空间哈希与拓扑缓存
算法
大熊背6 小时前
IspPipeline色相旋转模块实现
人工智能·算法·计算机视觉
爱学习的小白柏6 小时前
同城双活的核心不是双活,是逼着数据别出机房
大数据·人工智能·算法·langchain·ai编程
鹿角片ljp6 小时前
LeetCode 31:下一个排列|右找小,右找大,交换,右反转
java·数据结构·算法
橘子汽水1687 小时前
Leetcode 198,118打家劫舍,杨辉三角
算法·leetcode