Leetcode 257. Binary Tree Paths
题目链接
https://leetcode.com/problems/binary-tree-paths/description/
题目描述
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
题解
采用递归遍历,每次先判断是否到达根节点,如果到达根节点,就添加到List里面,然后清空新添加的字符,回到递归前的状态
代码
/**
* 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> list = new ArrayList<>();
if (root == null) {
return list;
}
StringBuilder sb = new StringBuilder();
findHelper(root, list, sb);
return list;
}
public void findHelper(TreeNode root, List<String> list, StringBuilder sb) {
if (root == null) { return ; }
int len = sb.length();
if (root.left == null && root.right == null) {
sb.append(root.val);
list.add(sb.toString());
sb.delete(len, sb.length());
return ;
}
sb.append(root.val).append("->");
findHelper(root.left, list, sb);
findHelper(root.right, list, sb);
sb.delete(len, sb.length());
}
}