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

    }


}

记录

总结

相关推荐
atunet9 分钟前
从算法优化到系统加速的多层级思考7
算法
Navigator_Z1 小时前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
Reart1 小时前
Leetcode 1143.最长公共子序列(720)
后端·算法
无相求码1 小时前
const vs #define:C语言常量定义的差异
c语言·算法
先吃饱再说2 小时前
LeetCode 226. 翻转二叉树
算法
剑锋所指,所向披靡!2 小时前
数据结构之关键路径
数据结构·算法
阿宇的技术日志2 小时前
漏桶、令牌桶、滑动窗口 三限流算法理解
算法·滑动窗口·漏桶·令牌桶
来一碗刘肉面2 小时前
队列的链式实现
数据结构·c++·算法·链表
KaMeidebaby2 小时前
卡梅德生物技术快报|原核膜蛋白表达优化实操手册,膜蛋白的纯化梯度洗脱完整流程
前端·网络·数据库·人工智能·算法
naturerun2 小时前
逐步插入回路法构造欧拉回路的算法
c++·算法