[LeetCode] Binary Tree Paths

来源:互联网 发布:淘宝v2贷款怎么搞 编辑:程序博客网 时间:2024/06/06 02:13

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”]

解题思路

先序遍历,递归的过程中保存路径,遇到叶子节点时将路径加入结果集。

实现代码

Java:

// Runtime: 3 ms/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private List<String> paths = new ArrayList<String>();    public List<String> binaryTreePaths(TreeNode root) {        if (root != null) {            traverse(root, String.valueOf(root.val));        }        return paths;    }    private void traverse(TreeNode root, String path) {        if (root.left == null && root.right == null) {            paths.add(path);        }        if (root.left != null) {            traverse(root.left, path + "->" + root.left.val);        }        if (root.right != null) {            traverse(root.right, path + "->" + root.right.val);        }    }}
1 0