LeetCode刷题实战257:二叉树的所有路径
共 2971字,需浏览 6分钟
·
2021-05-10 14:33
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
解题
/**
* 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 LinkedList<>();
helper(root, "", list);
return list;
}
private void helper(TreeNode root, String s, List<String>list){
if (root == null){
return;
}
s = s + root.val;
if (root.left == null && root.right == null){
list.add(s);
return;
}
if (root.left != null){
helper(root.left, s + "->", list);
}
if (root.right != null){
helper(root.right, s + "->", list);
}
}
}