• Binary Tree Paths


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

    For example, given the following binary tree:

       1
     /   
    2     3
     
      5
    

    All root-to-leaf paths are:

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

    Analyse: Recursion.

    Runtime: 4ms.

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<string> binaryTreePaths(TreeNode* root) {
    13         vector<string> result;
    14         if(!root) return result;
    15         
    16         dfs(root, result, "");
    17         return result;
    18     }
    19     void dfs(TreeNode* root, vector<string>& result, string temp){
    20         if(!root) return;
    21         
    22         temp = temp + std::to_string(root->val);
    23         if(root->left) dfs(root->left, result, temp + "->");
    24         if(root->right) dfs(root->right, result, temp + "->");
    25         if(!root->left && !root->right) result.push_back(temp);
    26     }
    27     /*string i2a(int val){
    28         if(val == 0) return "0";
    29         
    30         string result;
    31         if(val < 0){
    32             result += "-";
    33             val = -val;
    34         }
    35         while(val){
    36             result += val % 10 + '0';
    37             val /= 10;
    38         }
    39         int i = 0;
    40         if(result[0] = '-') i = 1;
    41         for(int j = result.length() - 1; i <= j; i++, j--){
    42             swap(result[i], result[j]);
    43         }
    44         return result;
    45     }*/
    46 };
  • 相关阅读:
    SQLite数据库
    如何将大文件写入到数据库中
    Visual Studio 2008 附加进程调试
    VS2010MFC编程入门
    关于exe文件传递参数方法
    监视剪贴板数据
    Delphi快捷键
    判断一个对象是否存在, 谁更快
    全局探色器
    用DELPHI中实现RAR文件解压到指定一目录
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4757223.html
Copyright © 2020-2023  润新知