二叉树的所有路径
给一棵二叉树,找出从根节点到叶子节点的所有路径。
样例
给出下面这棵二叉树:
1
/
2 3
5
所有根到叶子的路径为:
[
"1->2->5",
"1->3"
]
解题
深度优先 可以转换成先序遍历:根左右,根结点遍历以后,遍历两个子树,是叶子结点的时候保存路径
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root the root of the binary tree * @return all root-to-leaf paths */ public ArrayList<String> binaryTreePaths(TreeNode root) { // Write your code here ArrayList<String> result = new ArrayList<String>(); if(root == null) return result; String path=""; Paths(root,result,path); return result; } public void Paths(TreeNode root,ArrayList<String> result,String path){ if(root == null) return; if(root.left==null && root.right == null){ if( path.equals("")) path += root.val; else path +="->"+root.val; result.add(path); return; } if( path.equals("")) path += root.val; else path +="->"+root.val; Paths(root.left,result,path); Paths(root.right,result,path); } }
后面两行代码互换对结果没有影响,只是所有路径的先后次序发生了变化
Paths(root.right,result,path);
Paths(root.left,result,path);