• LintCode: Binary Tree Paths


    C++

     1 /**
     2  * Definition of TreeNode:
     3  * class TreeNode {
     4  * public:
     5  *     int val;
     6  *     TreeNode *left, *right;
     7  *     TreeNode(int val) {
     8  *         this->val = val;
     9  *         this->left = this->right = NULL;
    10  *     }
    11  * }
    12  */
    13 class Solution {
    14 public:
    15     /**
    16      * @param root the root of the binary tree
    17      * @return all root-to-leaf paths
    18      */
    19     vector<string> binaryTreePaths(TreeNode* root) {
    20         // Write your code here
    21         vector<string> result;
    22         if (root == NULL) {
    23             return result;
    24         }
    25         string path="";
    26         binaryTreePathsCore(root, result, path);
    27         return result;
    28     }
    29     void binaryTreePathsCore(TreeNode* root, vector<string> &result, string path) {
    30         if (root == NULL) {
    31             return;
    32         }
    33         int i = root->val;
    34         char a[5];
    35         // itoa(i, a, 10);
    36         sprintf(a, "%d", i);
    37         if ("" == path) {
    38             path = a;
    39         } else {
    40             path = path + "->" + a;
    41         }
    42         if (root->left == NULL && root->right == NULL) {
    43             result.push_back(path);
    44             return;
    45         }
    46         if (root->left != NULL) {
    47             binaryTreePathsCore(root->left, result, path);
    48         }
    49         if (root->right != NULL) {
    50             binaryTreePathsCore(root->right, result, path);
    51         }
    52         
    53         
    54     }
    55 };
  • 相关阅读:
    [JLOI2010] 冠军调查
    [ZJOI2009] 狼和羊的故事
    [CF1451D] Circle Game
    [CF1451E1] Bitwise Queries (Easy Version)
    [CF343D] Water Tree
    [CF1344B] Monopole Magnets
    [CF191C] Fools and Roads
    [CF1370D] Odd-Even Subsequence
    [CF1366D] Two Divisors
    [CF1359D] Yet Another Yet Another Task
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/5000030.html
Copyright © 2020-2023  润新知