[LeetCode257] Binary Tree Paths

来源:互联网 发布:伟哥影响生育吗 知乎 编辑:程序博客网 时间:2024/05/18 03:59

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


/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    List<String> result = new LinkedList<>();    List<Integer> path = new LinkedList<>();    public List<String> binaryTreePaths(TreeNode root) {        if(root ==null) return result;        getPaths(root);        return result;    }    public void getPaths(TreeNode node){        if(node == null) return;        path.add(node.val);        if(node.left == null && node.right == null){            StringBuffer buffer = new StringBuffer();            for(int i=0;i<path.size();i++){                if(i!=0)                    buffer.append("->");                buffer.append(path.get(i));            }            result.add(buffer.toString());        }        getPaths(node.left);        getPaths(node.right);        path.remove(path.size()-1);    }}


0 0