• 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 };
  • 相关阅读:
    Linux之uboot分析与移植20160601
    华为C语言编程规范
    中兴软件编程规范C/C++
    枚举esum20160530
    GPS之NMEA协议20160526
    uC/OS-II之系统函数20160526
    UART,USART,SPI,I2C等总线的介绍与区别20160526
    JAVA中使用JSON进行数据传递
    Android:单元测试Junit的配置
    IntentService简介
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4757223.html
Copyright © 2020-2023  润新知