zoukankan      html  css  js  c++  java
  • 257. 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"]

    输出所有根节点到叶子节点的路径

    C++(6ms):
     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>& res ,TreeNode* root , string t) {
    13         if (!root->left && !root->right){
    14             res.push_back(t) ;
    15             return ;
    16         }
    17         if (root->left) binaryTreePaths(res,root->left,t + "->" + to_string(root->left->val)) ;
    18         if (root->right) binaryTreePaths(res,root->right,t + "->" + to_string(root->right->val)) ;
    19     }
    20         
    21     vector<string> binaryTreePaths(TreeNode* root) {
    22         vector<string> res ;
    23         if (!root)
    24             return res ;
    25         binaryTreePaths(res,root,to_string(root->val)) ;
    26         return res ;
    27     }
    28 };
  • 相关阅读:
    构建CMDB的一些启发
    一个NB的安全认证机制
    SQLAlchemy
    Tornado基本使用
    Tornado源码探寻(请求到来)
    Tornado源码探寻(准备阶段)
    Tornado源码探寻(开篇)
    我的个人博客网站
    IDEA/AS快捷键收集&习惯
    ubuntu命令收集
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8031858.html
Copyright © 2011-2022 走看看