首页 > 其他 > 详细

Binary Tree Paths

时间:2015-11-25 01:06:24      阅读:285      评论:0      收藏:0      [点我收藏+]

Given a binary tree, return all root-to-leaf paths.

Given the following binary tree:

   1
 /   2     3
   5

All root-to-leaf paths are:

[ "1->2->5", "1->3" ]

解题思路:这道题目应该就是单纯的二叉树遍历,从根节点出发,遍历左右子节点并记录遍历路径,递归调用至叶节点;

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13   
14     List<String> res = new ArrayList<String>();
15     public List<String> binaryTreePaths(TreeNode root) {
16         // Write your code here
17         if(root != null) findPaths(root,String.valueOf(root.val));
18         return res;
19     }
20     public void findPaths(TreeNode n,String path){
21         if(n.left==null && n.right==null)   res.add(path);
22         if(n.right!=null)   findPaths(n.right,path+"->"+n.right.val);
23         if(n.left!= null)   findPaths(n.left ,path+"->"+n.left.val);
24     }
25 }

 

 

Binary Tree Paths

原文:http://www.cnblogs.com/wangnanabuaa/p/4993414.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!