zoukankan      html  css  js  c++  java
  • Leetcode 257 Binary Tree Paths 二叉树 DFS

    找到所有根到叶子的路径

    深度优先搜索(DFS), 即二叉树的先序遍历。

     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> vs_;
    13     void dfs(TreeNode* root, string s){
    14         if(!root) return;
    15         if(!root->left && !root->right){
    16            char t[20] = "";
    17            sprintf(t, "->%d", root->val);
    18            vs_.push_back(s + string(t));
    19            return;
    20         }
    21         else{
    22            char t[20] = "";
    23            sprintf(t, "->%d", root->val);
    24            dfs(root->left, s + string(t));
    25            dfs(root->right, s + string(t));
    26         }
    27     }
    28     vector<string> binaryTreePaths(TreeNode* root) {
    29         vs_.clear();
    30         if(!root) return vs_;
    31         char t[20] = "";
    32         sprintf(t, "%d", root->val);
    33         string s(t);
    34         if(!root->left && !root->right){
    35             vs_.push_back(s);
    36             return vs_;  
    37         } 
    38         dfs(root->left, s);
    39         dfs(root->right, s);
    40         return vs_;
    41     }
    42 };
  • 相关阅读:
    课二 计算机硬件组成余下
    课一 计算机硬件组成
    电梯演讲视频
    团队成员个人介绍
    day-65Django
    day-64Django
    day-63Django
    day-62Django
    day-61Django
    day-60Django
  • 原文地址:https://www.cnblogs.com/onlyac/p/5293468.html
Copyright © 2011-2022 走看看