zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    例20:希尔排序
    例19:直接插入排序
    例14:计算某日是该年的第几天
    为自己
    hdoj--1027--Ignatius and the Princess II(dfs)
    UESTC--758--P酱的冒险旅途(模拟)
    nyoj--990--蚂蚁感冒(模拟)(思维题)
    历届试题 邮局(dfs+剪枝)
    历届试题 数字游戏
    历届试题 回文数字
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4757223.html
Copyright © 2011-2022 走看看