LeetCode 257. Binary Tree Paths 递归过程保存信息

来源:互联网 发布:彩票遗漏数据价值 编辑:程序博客网 时间:2024/06/14 20:32

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

题意

给定一个二叉树,返回根节点到叶子结点间的路径

思路

  • 重点在于递归的过程,如何保持信息。
  • 关于递归过程的return,要注意返回到哪里,返回给谁。
  • 同样分解为子问题

代码

class Solution {public:    vector<string> binaryTreePaths(TreeNode* root)     {        vector<string> res;        if(root == NULL)  //当前结点为空,表示本身就是一颗空树,这个时候返回res,res内也没任何元素        {            return res;        }        if(root->left == NULL && root->right == NULL)  //当前结点是叶子结点,将当前结点的值存入vector<string>中,便于返回left,right        {            res.push_back(to_string(root->val));            return res;        }        vector<string> left =  binaryTreePaths(root->left); //获取当前结点左子树的路径        //遍历一遍当前节点左子树存储的路径,转换为当前节点到左子树的路径        for(int i=0;i<left.size();i++)        {            res.push_back(to_string(root->val)+"->"+left[i]);        }        vector<string> right =  binaryTreePaths(root->right); //获取当前结点右子树的路径        for(int i=0;i<right.size();i++)        {            res.push_back(to_string(root->val)+"->"+right[i]);        }        return res;    }};

结果

这里写图片描述

原创粉丝点击