标签:traversal def val ini init 治法 col rsa public
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
分治法。注意一下叶子节点和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; } }
lintcode480- Binary Tree Paths- easy
标签:traversal def val ini init 治法 col rsa public
原文地址:http://www.cnblogs.com/jasminemzy/p/7637357.html