lintcode480- Binary Tree Paths- easy

Given a binary tree, return all root-to-leaf paths.

Example

Given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

[
  "1->2->5",
  "1->3"
]
Tags 
Binary Tree Facebook Binary Tree Traversal Google

分治法。注意一下叶子节点和null节点这次处理不太一样而已。

1.如果是list<String> result; 不能直接result.add(Integer)!但result.add("" + Integer);可以。 result.add(Integer + s)也可以。不能直接塞一个其他类型,前面加空或者其他部分有加该类型是帮你说了要类型转换。

 

/**
 * 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) {
        // write your code here
        
        List<String> result = new ArrayList<String>();
        
        if (root == null) {
            return result;
        }
        
        if (root.left == null && root.right == null) {
            result.add("" + root.val);
            return result;
        }
        
        List<String> left = binaryTreePaths(root.left);
        List<String> right = binaryTreePaths(root.right);
        for (String s : left) {
            result.add(root.val + "->" + s);
        }
        for (String s : right) {
            result.add(root.val + "->" + s);
        }
        return result;
    }
}

 

 

 


posted @ 2017-10-08 14:34  jasminemzy  阅读(151)  评论(0编辑  收藏  举报