zoukankan      html  css  js  c++  java
  • 力扣257题(二叉树的所有路径)

    257、二叉树的所有路径

    具体实现:

    1.递归函数参数和返回值

    参数:根节点,记录每一条路径的path,存放结果集的result

    返回值:无

    2.递归终止条件

    遍历到叶子节点,也就是这个节点没有左孩子和右孩子时

    3.单层递归逻辑

    代码:

    class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<>();
            if(root == null) return res;
            List<Integer> paths = new ArrayList<>();
            traversal(root,paths,res);
            return res;
        }
        private void traversal(TreeNode root, List<Integer> paths, List<String> res){
            paths.add(root.val);
            if (root.left == null && root.right == null){
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < paths.size() - 1; i++){
                    sb.append(paths.get(i)).append("->");
                }
                sb.append(paths.get(paths.size()-1));
                res.add(sb.toString());
                return;
            }
            if (root.left != null){
                traversal(root.left, paths, res);
                paths.remove(paths.size() -1);
            }
            if (root.right != null){
                traversal(root.right, paths, res);
                paths.remove(paths.size() -1);
            }
        }
    }

     

  • 相关阅读:
    mkdir命令
    pwd命令
    chmod命令
    chown命令
    chgrp命令
    687. Longest Univalue Path
    HYSBZ 1036 树的统计Count (水题树链剖分)
    POJ 3709 K-Anonymous Sequence (斜率优化DP)
    LightOJ 1065 Island of Survival (概率DP?)
    LightOJ 1248 Dice (III) (水题,期望DP)
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15531125.html
Copyright © 2011-2022 走看看