[leetcode] 257. Binary Tree Paths

来源:互联网 发布:lol代练接单软件 编辑:程序博客网 时间:2024/06/05 12:50

题目:

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"]
1.采用递归左子树递归找到路径(根节点+左子树)右子树递归找到路径(根节点+右子树)2.递归停止条件:递归到叶子节点时终止,即root.left==null && root.right == null时,将字符串add到result中。

public List<String> binaryTreePaths(TreeNode root){List<String> list=new ArrayList<String>();findPath(root,"",list);return list;}public void findPath(TreeNode node,String curPath,List<String> list){if(node==null)return;if(node.left==null&&node.right==null){list.add(curPath+node.val);return;}findPath(node.left,curPath+node.val+"->",list);findPath(node.right,curPath+node.val+"->",list);}