LintCode | 480. 二叉树的所有路径

来源:互联网 发布:矩阵的秩和方程组的解 编辑:程序博客网 时间:2024/06/06 08:42

给一棵二叉树,找出从根节点到叶子节点的所有路径。
题目链接

可参考376题一起做

/*** Definition of TreeNode:* public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     }* }*/public class Solution {    /**     * @param root the root of the binary tree     * @return all root-to-leaf paths     */    public List<String> binaryTreePaths(TreeNode root) {        List<String> list = new ArrayList<String>();        if(root != null) {            String temp = "" + root.val;            findWay(list, temp, root);        }        return list;    }    private void findWay(List<String> list, String way, TreeNode node) {        if(node.left != null && node.right != null) {            String copy = way.toString();            way = way + "->" + node.left.val;            copy = copy + "->" + node.right.val;            findWay(list, way, node.left);            findWay(list, copy, node.right);        } else if(node.left != null && node.right == null) {            way = way + "->" + node.left.val;            findWay(list, way, node.left);        } else if(node.left == null && node.right != null) {            way = way + "->" + node.right.val;            findWay(list, way, node.right);        } else {            list.add(way);        }    }}
0 0