57. Binary Tree Paths - Jake blog - Java coding practice log (2017)" /> 57. Binary Tree Paths - Jake blog - Java coding practice log (2017)" />

257. 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']

This problem can be solved directly using 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 binaryTreePaths(TreeNode root) { List res= new ArrayList(); if(root != null){ DFS(root,'',res); } return res; } public void DFS(TreeNode root, String val, List res){ if(root.left == null && root.right == null){ res.add(val+root.val); } if(root.left != null){ DFS(root.left, val+ root.val+'->',res); } if(root.right != null){ DFS(root.right, val+ root.val+'->',res); } } }

This websiteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:"257. Binary Tree Paths"

245
0 0 245

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top