lintcode:二叉樹的所有路徑


二叉樹的所有路徑

給一棵二叉樹,找出從根節點到葉子節點的所有路徑。

樣例

給出下面這棵二叉樹:

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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM