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);
            }
        }
    }
  • 相关阅读:
    Win32汇编
    Boost ASIO 实现异步IO远控
    Python 使用oslo.vmware管理ESXI虚拟机
    Python 巡检接入钉钉机器人
    Django Ajax序列化与反序列化
    Nacos 认证绕过
    Lanproxy 遍历目录漏洞 CVE-2021-3019 附批量POC
    Apache Solr 全版本任意读取文件漏洞
    垂直水平居中的多种方法 主要的4种
    vue provide/inject 父组件如何给孙子组件传值
  • 原文地址:https://www.cnblogs.com/luo-c/p/12883049.html
Copyright © 2011-2022 走看看