• 257. Binary Tree Paths


    #week18

    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"]

    分析:

    这是一题比较简单的递归

    通过递归来求解二叉树路径

    题解:

     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     void binaryTreePaths(vector<string>& result, TreeNode* root, string t) {
    13         if (!root->left && !root->right) {
    14             result.push_back(t);
    15             return ;
    16         }
    17         
    18         if (root->left) binaryTreePaths(result, root->left, t + "->" + to_string(root->left->val));
    19         if (root->right) binaryTreePaths(result, root->right, t + "->" + to_string(root->right->val));
    20         
    21     }
    22     vector<string> binaryTreePaths(TreeNode* root) {
    23         vector<string> result;
    24         if (!root) return result;
    25         
    26         binaryTreePaths(result, root, to_string(root->val));
    27         return result;
    28     }
    29 };
  • 相关阅读:
    CodeForces
    CodeForces
    CodeForces 718C && HDU 3572 && Constellation
    CodeForces
    USACO 5.4 tour的dp解法
    10.22~10.28一周经典题目整理(meeting,BZOJ4377,POJ3659)
    codeforces 724D
    codeforces 724C
    hdu5909 Tree Cutting
    hdu5822 color
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278280.html
Copyright © 2020-2023  润新知