Binary Tree Paths leetcode
文章目录
Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"]
深度优先搜索
复杂度
时间O(n) 空间栈O(n logn)
代码
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
if (root == null) {
return res;
}
String str = root.val +"";
helper(res, root, str);
return res;
}
public void helper(List<String> res, TreeNode root, String str) {
if (root.left == null && root.right == null) {
res.add(str);
return;
}
if (root.left != null) {
helper(res, root.left, str + "->" + root.left.val);
}
if (root.right != null) {
helper(res, root.right, str +"->" + root.right.val);
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论