題目
給一棵二叉樹桨醋,找出從根節(jié)點到葉子節(jié)點的所有路徑肖爵。
樣例
給出下面這棵二叉樹:
binaryTree1.PNG
所有根到葉子的路徑為:
binaryTree2.PNG
分析
顯然本道題可以使用遞歸算法待逞。每天路徑結(jié)束的條件的是遇到葉子節(jié)點,該樹有多少個葉子節(jié)點就會有多少路徑导梆。
分別遞歸求解左子樹和右子樹滓彰。
代碼
/**
* 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 List<String> binaryTreePaths(TreeNode root) {
// Write your code here
List result = new ArrayList<String>();
if(root == null)
return result;
binaryTreePathsCore(root,result, root.val + "" );
return result;
}
void binaryTreePathsCore(TreeNode root,List<String> str,String strpath)
{
if(root.left==null&&root.right==null)//葉子結(jié)點
{
str.add(strpath);
return;
}
if(root.left!=null)
binaryTreePathsCore(root.left,str,strpath+"->"+ root.left.val);
if(root.right!=null)
binaryTreePathsCore(root.right,str,strpath+"->"+ root.right.val);
}
}