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

来源:互联网 发布:c语言结果取绝对值 编辑:程序博客网 时间:2024/05/30 05:02

题目:

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 stubTreeNode 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);}  }


0 0
原创粉丝点击