leetcode-257. Binary Tree Paths

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"]
输出所有根节点到叶子节点的路径
java代码:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> answer=new ArrayList<String>();
        if(root!=null)searchBT(root,"",answer);
        return answer;
    }
    private void searchBT(TreeNode root,String path,List<String> answer){//深度优先搜索
	    if(root.left==null&&root.right==null)answer.add(path+root.val);
	    if(root.left!=null)searchBT(root.left,path+root.val+"->",answer);
	    if(root.right!=null)searchBT(root.right,path+root.val+"->",answer);
    }
}

  

原文地址:https://www.cnblogs.com/lcbg/p/6592106.html