zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    Linux嵌入式 -- 内核
    Linux嵌入式 -- 内核
    utf8和utf8mb4区别
    二叉树的实现
    python资源大全2
    树与树算法
    二叉树
    70.最小生成树
    68.营救问题(广搜)
    67.迷宫问题(广搜)
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/5000030.html
Copyright © 2011-2022 走看看