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

    答案:
    和遍历类似,用递归的思路,深度优先搜索的算法
     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>str;
    14         if(root==NULL){
    15             return str;
    16         }
    17         DFS(root,"",str);
    18         return str;
    19     }
    20     void DFS(TreeNode *node,string temp, vector<string>&str){
    21         if(node->left==NULL&&node->right==NULL){
    22             str.push_back(temp+to_string(node->val));
    23         }
    24         if(node->left!=NULL){
    25             DFS(node->left,temp+to_string(node->val)+"->",str);
    26         }
    27         if(node->right!=NULL){
    28             DFS(node->right,temp+to_string(node->val)+"->",str);
    29         }
    30     }
    31 };
    
    
    
     
  • 相关阅读:
    P3332 [ZJOI2013]K大数查询
    树上最短路---------------树链剖分,优化建边。
    BZOJ_4386
    2016_1_13(3)
    2016_1_13(2)
    2016_1_13
    BZOJ_1698
    BZOJ_4152
    BZOJ_3110
    BZOJ_2141
  • 原文地址:https://www.cnblogs.com/Reindeer/p/5728535.html
Copyright © 2011-2022 走看看