leetcode 257 Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
递归方法:
1、递归终止条件,root是否为空,及是否为叶子结点
2、递归过程
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
if(root == null)
return res;
if(root.left == null && root.right == null){
res.add(root.val + "");
return res;
}
List<String> leftS = binaryTreePaths(root.left);
for(int i=0;i<leftS.size();i++){
res.add(root.val + "->" + leftS.get(i));
}
List<String> rightS = binaryTreePaths(root.right);
for(int i=0;i<rightS.size();i++){
res.add(root.val + "->" + rightS.get(i));
}
return res;
}
}
submission中 深度优先遍历DFS:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new LinkedList<>();
dfs(result, root, "");
return result;
}
private void dfs(List<String> result, TreeNode node, String s) {
if (node == null) return;
String built = s.length() == 0 ? s + node.val : s + "->" + node.val;
if (node.left == null && node.right == null) {
result.add(built);
} else {
dfs(result, node.left, built);
dfs(result, node.right, built);
}
}
}
还没有评论,来说两句吧...