LintCode | 480. 二叉樹的所有路徑

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

可參考376題一起做

/**
* 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) {
        List<String> list = new ArrayList<String>();
        if(root != null) {
            String temp = "" + root.val;
            findWay(list, temp, root);
        }
        return list;
    }

    private void findWay(List<String> list, String way, TreeNode node) {
        if(node.left != null && node.right != null) {
            String copy = way.toString();
            way = way + "->" + node.left.val;
            copy = copy + "->" + node.right.val;
            findWay(list, way, node.left);
            findWay(list, copy, node.right);
        } else if(node.left != null && node.right == null) {
            way = way + "->" + node.left.val;
            findWay(list, way, node.left);
        } else if(node.left == null && node.right != null) {
            way = way + "->" + node.right.val;
            findWay(list, way, node.right);
        } else {
            list.add(way);
        }
    }
}
發佈了84 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章