zoukankan      html  css  js  c++  java
  • Leetcode 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"]
    分析:典型的深度优先搜索,dfs函数思路为:
    dfs函数中参数传入一个string,该String将每次结点的值连接起来,直到递归出口的时候返回;
    当该结点有左孩子的时候,将左孩子的值连接到字符串尾部;
    当该结点有右孩子的时候,将右孩子的值连接到字符串尾部;
    当该结点无左右孩子的时候,将字符串push入数组后return;
     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 dfs(vector<string> &v, TreeNode* root, string s){
    13         if(root -> left == NULL && root -> right == NULL){
    14             v.push_back(s);
    15             return;
    16         }
    17         if(root -> left != NULL)
    18             dfs(v, root -> left, s + "->" + to_string(root -> left -> val));
    19         if(root -> right != NULL)
    20             dfs(v, root -> right, s + "->" + to_string(root -> right -> val));
    21     }
    22     vector<string> binaryTreePaths(TreeNode* root) {
    23         vector<string> v;
    24         if(root == NULL)
    25             return v;
    26         dfs(v, root, to_string(root -> val));
    27         return v;
    28     }
    29 };
     
  • 相关阅读:
    如何解决js跨域问题
    前端开发群推荐:鬼懿IT
    Highcharts中文API详解
    搜索弹层交互
    js中判断Object、Array、Function等引用类型对象是否相等的方法
    各种之父
    UNIX简介
    MATLAB二维正态分布图
    Albert Einstein says
    GNU简介
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5815421.html
Copyright © 2011-2022 走看看