zoukankan      html  css  js  c++  java
  • [LeetCode] Binary Tree Paths

    The basic idea is to start from root and add it to the current path, then we recursively visit its left and right subtrees if they exist; otherwise, we have reached a leaf node, so just add the current path to the result paths.

    The code is as follows.

     1 class Solution {
     2 public:
     3     vector<string> binaryTreePaths(TreeNode* root) {
     4         vector<string> paths;
     5         string path;
     6         treePaths(root, path, paths);
     7         return paths;
     8     }
     9 private:
    10     void treePaths(TreeNode* node, string path, vector<string>& paths) {
    11         if (!node) return;
    12         path += path.empty() ? to_string(node -> val) : "->" + to_string(node -> val);
    13         if (!(node -> left) && !(node -> right)) {
    14             paths.push_back(path);
    15             return;
    16         }
    17         if (node -> left) treePaths(node -> left, path, paths);
    18         if (node -> right) treePaths(node -> right, path, paths);
    19     }
    20 };
  • 相关阅读:
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    教你搭建SpringSecurity3框架(附源码)
    浅谈数据库联合查询
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4733742.html
Copyright © 2011-2022 走看看