您的位置:首页 > 编程语言 > Java开发

二叉树的所有路径

2017-01-08 23:02 274 查看
package leetcode;

/**

* 题目

给一棵二叉树,找出从根节点到叶子节点的所有路径。

样例

给出下面这棵二叉树:



他的路径为:

[

“1->2->5”

“1->3”

]

*/

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class n7TreeNodePath {

public static void main(String[] args) {

TreeNode root=createTree();
List resultList=new ArrayList<String>();
if(root!=null){
treePath(root,resultList,root.val+"");
}
for(Object path:resultList){
System.out.println((String)path);
}

}

private static void treePath(TreeNode root, List resultList, String strpath) {
if(root.left==null&&root.right==null){
resultList.add(strpath);
return;
}
if(root.left!=null){
treePath(root.left,resultList,strpath+"->"+root.left.val);
}
if(root.right!=null){
treePath(root.right,resultList,strpath+"->"+root.right.val);
}

}

//用先序递归建树
public static TreeNode createTree(){
Scanner input=new Scanner(System.in);
String str=input.nextLine();// 输入一个数字
TreeNode node=null;
if(isNum(str)){//判断是否是数字,则用这个数字为根创建一个结点
node=new TreeNode(Integer.valueOf(str).intValue());
node.left=createTree();
node.right=createTree();
return node;
}
return node;

}
//先序遍历
public static void PreTraverse(TreeNode root){
if(root!=null){
System.out.printf("%4d",root.val);
PreTraverse(root.left);
PreTraverse(root.right);
}else{
System.out.printf("%2c",'#');
}
}

public static boolean isNum(String str){
return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?([.]([0-9]+))?)$");
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息