zoukankan      html  css  js  c++  java
  • 257.Binary Tree Paths

    给定一个二叉树,返回所有根节点到叶子节点的路径。
    Input:
     1
     /
    2  3

    5
    Output: ["1->2->5", "1->3"]
    Explanation: All root-to-leaf paths are: 1->2->5, 1->3

    难点:返回的是vector<string>的容器类型,需要对容器遍历读写操作。
    思路:运用3个容器,分别为接收左子树路径的 res_left,接收右子树路径的 res_right,和总的路径的 res. 对每次遍历所得到的 res_left 和 res_right 遍历,将里面的已有路径读出来,加上当前节点的值,再写入到总的路径容器 res 中,最后返回 res.

    vector<string> binaryTreePaths(TreeNode* root) {
        if (!root) return {};
        vector<string> res_left;
        vector<string> res_right;
        vector<string> res;
        if (root->left != NULL) res_left = binaryTreePaths(root->left);
        if (root->right != NULL) res_right = binaryTreePaths(root->right);
        if (res_left.size() == 0 && res_right.size() == 0) {
            return{ to_string(root->val) };
        }
        for (int i = 0; i < res_left.size(); i++) {
            res.push_back(to_string(root->val) + "->" + res_left[i]);
        }
        for (int i = 0; i < res_right.size(); i++) {
            res.push_back(to_string(root->val) + "->" + res_right[i]);
        }
        return res;
    }

    Java版:

    刷第二遍,感觉利用递归 + 深搜,将每一次遍历的路线都记录下来,当节点是叶子节点时,将记录下来的路径加到结果集中。

    class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> ans = new ArrayList<>();
            binaryTreePathsDFS(root, "", ans);
            return ans;
        }
    
        public void binaryTreePathsDFS(TreeNode root, String path, List<String> ans){
            if(root == null) return;
            path += root.val;
            if(root.left == null && root.right == null) ans.add(path);
            else{
                binaryTreePathsDFS(root.left, path+"->",ans);
                binaryTreePathsDFS(root.right, path+"->",ans);
            }
        }
    }
  • 相关阅读:
    python常用函数 A
    从__name__=='__main__'说到__builtin__
    python常用魔法函数
    MySQL内核:InnoDB存储引擎 卷1
    “胡”说IC——菜鸟工程师完美进阶
    恶意代码分析实战
    转折点:移动互联网时代的商业法则
    大型网站系统与Java中间件实践
    《Node.js实战(双色)》作者之一——吴中骅访谈录
    网站运维技术与实践
  • 原文地址:https://www.cnblogs.com/luo-c/p/12883049.html
Copyright © 2011-2022 走看看