Binary Tree Paths - Ryan的修炼之路
Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree: 1 / \2 3 \ 5All 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); }}