LeetCode 257 Binary Tree Paths

题目描述

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

分析

递归求解

代码

    List<String> rt = new ArrayList<String>();
    List<Integer> path = new ArrayList<Integer>();

    public List<String> binaryTreePaths(TreeNode root) {
        findPath(root);
        return rt;
    }

    void findPath(TreeNode root) {

        if (root == null) {
            return;
        }

        path.add(root.val);

        // 是一条路径,将path添加到rt中
        if (root.left == null && root.right == null) {
            StringBuffer sb = new StringBuffer();
            sb.append(path.get(0));
            for (int i = 1; i < path.size(); i++) {
                sb.append("->" + path.get(i));
            }
            rt.add(sb.toString());
        }

        findPath(root.left);
        findPath(root.right);

        path.remove(path.size() - 1);
    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/50273301
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞