Leetcode480-Binary Tree Paths-Easy
阿新 • • 發佈:2019-04-06
bsp main clas pub mod paths oda 註意 easy
480. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
Example
Example 1:
Input:
1
/ 2 3
5
Output:
[
"1->2->5",
"1->3"
]
Example 2:
Input:
1
/
2
Output:
[
"1->2"
]
註意:
因為題目的output格式 "1 -> 2",(有箭頭),所以用String來存儲每一個path。
遞歸法代碼:
/** * 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 */ ArrayList<String> result; public List<String> binaryTreePaths(TreeNode root) { result = new ArrayList<String>(); if (root == null) { return result; } String path= String.valueOf(root.val); helper(root, path); return result; } public void helper(TreeNode root, String path) { if (root.left == null && root.right == null) { result.add(path); return; } if (root.left != null) { helper(root.left, path + "->" + String.valueOf(root.left.val)); } if (root.right != null) { helper(root.right, path + "->" + String.valueOf(root.right.val)); } } }
Leetcode480-Binary Tree Paths-Easy