题解 | #二叉树根节点到叶子节点和为指定值的路径#

二叉树根节点到叶子节点和为指定值的路径

https://www.nowcoder.com/practice/840dd2dc4fbd4b2199cd48f2dadf930a

记录:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @param sum int整型
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
        // write code here
        ArrayList<ArrayList<Integer>> out = new ArrayList<>();
        if (root == null) {
            return out;
        } else {
            Stack<TreeNode> st = new Stack<>();
            Stack<ArrayList<Integer>> stp = new Stack<>();
            ArrayList<Integer> path = new ArrayList<>();
            path.add(root.val);
            st.add(root);
            stp.add(path);
            while (!st.isEmpty()) {
                TreeNode temp = st.pop();
                ArrayList<Integer> tempp = stp.pop();
                if (temp.left == null && temp.right == null) {
                    int sumtemp = tempp.stream().mapToInt(n -> n).sum();
                    if (sumtemp == sum) {
                        out.add(tempp);
                    }
                }
                if (temp.right != null) {
                    st.push(temp.right);
                    tempp.add(temp.right.val);
                    stp.push(new ArrayList<>(tempp));
                    tempp.remove(tempp.size() - 1);
                }
                if (temp.left != null) {
                    st.push(temp.left);
                    tempp.add(temp.left.val);
                    stp.push(new ArrayList<>(tempp));
                    tempp.remove(tempp.size() - 1);
                }
            }
            return out;
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 12:22
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-01 11:47
点赞 评论 收藏
分享
能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
程序员小白条:你不是有一段实习了吗,现在找中大厂实习?过段时间要秋招了
我的简历长这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务