1. 程式人生 > 實用技巧 >Leetcode 257 二叉樹的所有路徑

Leetcode 257 二叉樹的所有路徑

Leetcode 257 二叉樹的所有路徑

資料結構定義:

給定一個二叉樹,返回所有從根節點到葉子節點的路徑。

說明:葉子節點是指沒有子節點的節點。

示例:

輸入:

   1
 /   \
2     3
 \
  5

輸出: ["1->2->5", "1->3"]

解釋: 所有根節點到葉子節點的路徑為: 1->2->5, 1->3
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

遞迴寫法:

class Solution {
    List<String> result = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        if(root == null){
            return result;
        }
        dfs(root,new String());
        return result;
    }
    private void dfs(TreeNode root,String s){
        if(root == null){
            return;
        }
        StringBuilder sb =new StringBuilder(s);
        sb.append(root.val);
        if(root.left == null && root.right == null){
            result.add(sb.toString());
            return;
        }
        sb.append("->");
        dfs(root.left,sb.toString());
        dfs(root.right,sb.toString());
    }
}

廣度優先遍歷:

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        Queue<String> path = new LinkedList<>();
        nodeQueue.offer(root);
        path.offer(String.valueOf(root.val));
        while(!nodeQueue.isEmpty()){
            TreeNode node = nodeQueue.poll();
            String trail = path.poll();
            if(node.left == null && node.right == null){
                result.add(trail);
            }else{
                if(node.left != null){
                    nodeQueue.offer(node.left);
                    path.offer(new StringBuilder(trail)
                               .append("->")
                               .append(node.left.val)
                               .toString());
                }
                if(node.right != null){
                    nodeQueue.offer(node.right);
                    path.offer(new StringBuilder(trail)
                               .append("->")
                               .append(node.right.val)
                               .toString());
                }
            }
        }
        return result;
    }
}