zoukankan      html  css  js  c++  java
  • lc0306

    ✅ 257. 二叉树的所有路径

    https://leetcode-cn.com/problems/binary-tree-paths/https://leetcode-cn.com/problems/binary-tree-paths/

    描述

    给定一个二叉树,返回所有从根节点到叶子节点的路径。
    
    说明: 叶子节点是指没有子节点的节点。
    
    示例:
    
    输入:
    
       1
     /   
    2     3
     
      5
    
    输出: ["1->2->5", "1->3"]
    
    解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-paths
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    

    解答

    这就是个深度搜索吧?

    深度搜索 dfs 框架

    DFS(dep, otherArguments){
        if reachEnd:
            ...
            return
        else: # not reach end yet
            DFS(dep + 1, otherArguments)
    }
    //比如对 二叉树 进行DFS, 其框架是:
    DFS(root) {
        if root is None:
            return
        else:
            DFS(root.left)
            DFS(root.right)
    }
    

    官方解答

    方法一:递归
    最直观的方法是使用递归。在递归遍历二叉树时,需要考虑当前的节点和它的孩子节点。如果当前的节点不是叶子节点,则在当前的路径末尾添加该节点,并递归遍历该节点的每一个孩子节点。如果当前的节点是叶子节点,则在当前的路径末尾添加该节点后,就得到了一条从根节点到叶子节点的路径,可以把该路径加入到答案中。

    作者:LeetCode
    链接:https://leetcode-cn.com/problems/binary-tree-paths/solution/er-cha-shu-de-suo-you-lu-jing-by-leetcode/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    # 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]:
            def construct_path(root, path):
                if root:
                    path += str(root.val)
                    if not root.left and not root.right:
                        paths.append(path)
                    else:
                        path += '->'
                        construct_path(root.left, path)
                        construct_path(root.right, path)
            paths = []
            construct_path(root, "")
            return paths
    '''
    执行用时 :
    40 ms
    , 在所有 Python3 提交中击败了
    45.03%
    的用户
    内存消耗 :
    13.4 MB
    , 在所有 Python3 提交中击败了
    19.16%
    的用户
    '''
    

    方法二:迭代(todo rev me)
    上面的算法也可以使用迭代(宽度优先搜索)的方法实现。我们维护一个队列,存储节点以及根到该节点的路径。一开始这个队列里只有根节点。在每一步迭代中,我们取出队列中的首节点,如果它是一个叶子节点,则将它对应的路径加入到答案中。如果它不是一个叶子节点,则将它的所有孩子节点加入到队列的末尾。当队列为空时,迭代结束。

    作者:LeetCode
    链接:https://leetcode-cn.com/problems/binary-tree-paths/solution/er-cha-shu-de-suo-you-lu-jing-by-leetcode/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    class Solution:
        def binaryTreePaths(self, root):
            """
            :type root: TreeNode
            :rtype: List[str]
            """
            if not root:
                return []
            
            paths = []
            stack = [(root, str(root.val))]
            while stack:
                node, path = stack.pop()
                if not node.left and not node.right:
                    paths.append(path)
                if node.left:
                    stack.append((node.left, path + '->' + str(node.left.val)))
                if node.right:
                    stack.append((node.right, path + '->' + str(node.right.val)))
            
            return paths
    
    作者:LeetCode
    链接:https://leetcode-cn.com/problems/binary-tree-paths/solution/er-cha-shu-de-suo-you-lu-jing-by-leetcode/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    

    c todo reve me

    C,递归,4ms

    /最大的教训就是用C的话,返回的char**,必须是malloc得来的,刚开始我是直接char bin_tree_paths[100][100]
    结果它会说是执行出错,申请之后就没有这样了,其实题目也说了The returned array must be malloced
    /

    void dfs(struct TreeNode* root, char** bin_tree_paths, int* path, int* returnSize, int depth)
    {
        int i = 0;
        path[depth++] = root->val;  //主要是这个depth,depth在每一层的值都不一样的,跳回到哪层,depth就是哪一层的的值
        if(root->left == NULL && root->right == NULL)
        {
            bin_tree_paths[*returnSize] = (char*)malloc(sizeof(char) * 100);
            bin_tree_paths[*returnSize][0] = 0;
            for(i = 0; i < depth - 1; i++)
            {
                sprintf(bin_tree_paths[*returnSize], "%s%d->", bin_tree_paths[*returnSize], path[i]); //第一次用了sprintf,挺好用的
            }
            sprintf(bin_tree_paths[*returnSize], "%s%d", bin_tree_paths[*returnSize], path[i]); //最后一个不用箭头
            (*returnSize)++;
            return;
        }
        
        if(root->left != NULL)
        {
            dfs(root->left, bin_tree_paths, path, returnSize, depth);
        }
        
        if(root->right != NULL)
        {
            dfs(root->right, bin_tree_paths,path, returnSize, depth);
        }
        return;  //返回是void类型,其实这一步不写也行
    }
    
    char** binaryTreePaths(struct TreeNode* root, int* returnSize) 
    {
        int path[100] = {0}, depth = 0;
        char** bin_tree_paths = (char**)malloc(sizeof(char*) * 100);
        if(root == NULL)
        {
            return root;
        }
        *returnSize = 0;
        dfs(root, bin_tree_paths, path, returnSize, depth);
        return bin_tree_paths;
    }
    

    py

    这个递归 没有 完美地符合 一个递归写法: 在边界条件的时候,及时退出(aka,先写 退出语句)

    实际上写了,实际上令人难受的地方是,在递归中使用 了 for 迭代。 没有官方清晰。

    class Solution:
                
        def binaryTreePaths(self, root: TreeNode) -> List[str]:
            if not root:
                return []
            if not root.left and not root.right:
                return [str(root.val)]
            paths = []
            if root.left:
                for i in self.binaryTreePaths(root.left):
                    paths.append(str(root.val) + '->' + i)
            if root.right:
                for i in self.binaryTreePaths(root.right):
                    paths.append(str(root.val) + '->' + i)
            return paths 
    
  • 相关阅读:
    83. Remove Duplicates from Sorted List
    35. Search Insert Position
    96. Unique Binary Search Trees
    94. Binary Tree Inorder Traversal
    117. Populating Next Right Pointers in Each Node II
    116. Populating Next Right Pointers in Each Node
    111. Minimum Depth of Binary Tree
    169. Majority Element
    171. Excel Sheet Column Number
    190. Reverse Bits
  • 原文地址:https://www.cnblogs.com/paulkg12/p/12426210.html
Copyright © 2011-2022 走看看