lintcode480- Binary Tree Paths- easy
生活随笔
收集整理的這篇文章主要介紹了
lintcode480- Binary Tree Paths- easy
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given a binary tree, return all root-to-leaf paths.
Example
Given the following binary tree:
1/ \ 2 3\5All 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;} }?
?
?
轉載于:https://www.cnblogs.com/jasminemzy/p/7637357.html
總結
以上是生活随笔為你收集整理的lintcode480- Binary Tree Paths- easy的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 超神线段树 山海经
- 下一篇: Cow Relays POJ - 361