从二叉树根节点搜索到指定结点的路径

LC 236题,二叉树的最近公共祖先:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/

其中一种解法的关键,是找到从根节点到指定结点的路径。

 

    public static boolean findPath(TreeNode root, TreeNode target, Stack<TreeNode> stack){
        boolean found = false;
        if (root != null){
            if (root.val == target.val || findPath(root.left, target, stack) || findPath(root.right, target, stack)){
                stack.push(root);
                found = true;
            }
        }
        return found;
    }

 

posted on 2022-08-13 18:59  浪荡绅士  阅读(48)  评论(0)    收藏  举报

导航