1. 程式人生 > >[LeetCode] Binary Tree Paths 二叉樹路徑

[LeetCode] Binary Tree Paths 二叉樹路徑

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

 

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

圖形化表述:

import java.util.List;
import java.util.ArrayList;
public class liubobo_7_4 {

/// 257. Binary Tree Paths
/// https://leetcode.com/problems/binary-tree-paths/description/
/// 時間複雜度: O(n), n為樹中的節點個數
/// 空間複雜度: O(h), h為樹的高度

    // Definition for a binary tree node.
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    public List<String> binaryTreePaths(TreeNode root) {

        ArrayList<String> res = new ArrayList<String>();

        if(root == null)//遞迴終止條件,防止放入空樹
            return res;

        if(root.left == null && root.right == null){//遞迴終止條件,判斷有沒有到達葉子節點
            res.add(Integer.toString(root.val));
            return res;
        }

        List<String> leftPaths = binaryTreePaths(root.left);//返回所有左子樹的路徑
        for(String s: leftPaths){
            StringBuilder sb = new StringBuilder(Integer.toString(root.val));
            sb.append("->");
            sb.append(s);
            res.add(sb.toString());
        }

        List<String> rightPaths = binaryTreePaths(root.right);//返回所有右子樹的路徑
        for(String s: rightPaths) {
            StringBuilder sb = new StringBuilder(Integer.toString(root.val));
            sb.append("->");
            sb.append(s);
            res.add(sb.toString());
        }

        return res;
    }

}

類似題目:

1.path sum II

2.sum root to leaf numbers