题目链接:https://leetcode.com/submissions/detail/37771540/
题目:
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"]
题意:找出给定二叉树中的所有路径
分析:遍历每个节点,记录其路径(如果当前节点有子节点,则调用递归继续遍历其子节点,并记录新路径,删除之前路径)
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<>(); if(root==null) return result; searchPaths(root, "", result); return result; } public void searchPaths(TreeNode root, String curPath, List<String> result) { String updatePath; if(root.left == null && root.right == null) { updatePath = curPath + root.val; result.add(updatePath); result.remove(curPath); } if(root.left != null || root.right != null) { updatePath = curPath + root.val + "->"; result.add(updatePath); result.remove(curPath); if(root.left != null) searchPaths(root.left, updatePath, result); if(root.right != null) searchPaths(root.right, updatePath, result); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/yangyao_iphone/article/details/48028729