码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode257 BinaryTreePaths(打印根节点到叶子节点的左右路径) Java题解

时间:2015-08-20 22:38:02      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:binarytreepaths   leetcode   java   深度优先   

题目:

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"]
题解:

用深度优先遍历,类似二叉树的前序变遍历

代码:

public class LeetCode257_BinaryTreePaths {
	 static List<String> paths=new ArrayList<>();
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode p1=new TreeNode(1);
		TreeNode p2=new TreeNode(2);
//		TreeNode p3=new TreeNode(3);
//		TreeNode p4=new TreeNode(5);
		p1.left=p2;
//		p1.right=p3;
//		p2.left=p4;
		
		binaryTreePaths(p1);

	}
	
	 public static  List<String> binaryTreePaths(TreeNode root) {
		
		 if(root==null)
			 return paths;
		 String curPath="";
		 serachTree(root, curPath);
		 return paths;
		 
		 
		
	    }
	 
	 public static void serachTree(TreeNode root,String currentPath) {
		 
		 currentPath+=root.val;
		 if(root.left==null&&root.right==null)
		 {
			 paths.add(currentPath);
			 System.out.println(currentPath);
			 return;
		 }
		 currentPath+="->";
		 if(root.left!=null)
			 serachTree(root.left, currentPath);
		 if(root.right!=null)
			 serachTree(root.right, currentPath);
		
	}
	 
	 

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode257 BinaryTreePaths(打印根节点到叶子节点的左右路径) Java题解

标签:binarytreepaths   leetcode   java   深度优先   

原文地址:http://blog.csdn.net/u012249528/article/details/47816499

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!