LeetCode #257 Binary Tree Paths 二叉树的所有路径

257 Binary Tree Paths 二叉树的所有路径

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

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

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

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

题目描述:
给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

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

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

思路:

采用深度优先遍历(dfs)
时间复杂度O(n), 空间复杂度O(n)

代码:
C++:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution 
{
public:
    vector<string> binaryTreePaths(TreeNode* root) 
    {
        vector<string> result;
        if (!root) return result;
        vector<string> left = binaryTreePaths(root -> left);
        vector<string> right = binaryTreePaths(root -> right);
        string temp = to_string(root -> val);
        if (!left.empty()) for (int i = 0; i < left.size(); i++) result.push_back(temp + "->" + left[i]);
        if (!right.empty()) for (int i = 0; i < right.size(); i++) result.push_back(temp + "->" + right[i]);
        if (left.empty() && right.empty()) result.push_back(temp);
        return result;
    }
};

Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        String temp = "";
        dfs(root, temp, result);
        return result;
    }

    private void dfs(TreeNode root, String temp, List<String> list) {
        if (root == null) return;
        temp += root.val;
        if (root.left == null && root.right == null) {
            list.add(temp);
            return;
        } else {
            dfs(root.left, temp + "->", list);
            dfs(root.right, temp + "->", list);
        }
    }
}

Python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        result = []
        def dfs(root: TreeNode, path: List[str]) -> None:
            if not root:
                return
            if not root.left and not root.right:
                path.append(str(root.val))
                result.append('->'.join(path))
            dfs(root.left, path + [str(root.val)])
            dfs(root.right, path + [str(root.val)])
        dfs(root, [])
        return result
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录 简书的 markdown 都不支持 [TOC] 语法……我就不贴目录了。下面按照类别,列出了29道关于二叉树...
    被称为L的男人阅读 3,383评论 0 8
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,453评论 0 10
  • 树的基本概念 节点,根节点,父节点,子节点,兄弟节点都是属于树的范涛; 一棵树可以没有任何节点,称为空树; 一棵树...
    coder_feng阅读 1,142评论 0 0
  • 问题: Given a binary tree, return all root-to-leaf paths.Fo...
    Cloudox_阅读 214评论 0 0
  • 由此而始,蕊儿方真真正正的跟于嫂学起武技来,而阮晴也真真正正的领略到阮秋芷稳占花魁的精彩处。两个天赋奇佳的...
    冗舟阅读 448评论 0 1