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

    }


}

记录

总结

相关推荐
左左右右左右摇晃几秒前
数据结构——数组
数据结构·笔记·算法
nainaire4 分钟前
速通LeetCode hot100——(1~9 哈希,双指针,滑动窗口)
c++·笔记·算法·leetcode
2501_924952694 分钟前
分布式缓存一致性
开发语言·c++·算法
XiYang-DING1 小时前
【LeetCode】LCR 019. 验证回文串 II
算法·leetcode·职场和发展
灰色小旋风1 小时前
力扣18 四数之和(C++)
数据结构·算法·leetcode
噜啦噜啦嘞好1 小时前
算法篇:前缀和
数据结构·算法
重生之我是Java开发战士1 小时前
【广度优先搜索】FloodFill算法: 图像渲染,岛屿数量,岛屿的最大面积,被围绕的区域
算法·宽度优先
tankeven1 小时前
HJ147 最大 FST 距离
c++·算法
2401_857918291 小时前
分布式系统安全通信
开发语言·c++·算法