LeetCode刷题笔记(Binary Tree Paths)

今天刷了一道题,感觉编程思路还是有些绕,下面就和大家分享一下经验吧!

题目如下:

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

题意分析:

给定一个二叉树,请返回所有从根节点到叶子节点的路径。

方法一(递归法)

分别对根节点的左右子树进行递归调用,将两部分递归所得的路径结果直接与根节点值拼接得到所有从根节点到叶子节点的路径。其中递归终止条件:若判断当前节点为叶子节点,则将其值存入res中并返回res。

解题代码如下:

class Solution{
public:
    vector<string> binaryTreePaths(TreeNode* root){
        vector<string> res;
        if(root == NULL) return res;
        if(root->left == NULL && root->right == NULL) {res.push_back(to_string(root->val)); return res;}

        vector<string> leftpath = binaryTreePaths(root->left);
        for (int i = 0; i < leftpath.size(); i++) res.push_back(to_string(root->val) + "->" + leftpath[i]);
        vector<string> rightpath = binaryTreePaths(root->right);
        for (int i = 0; i < rightpath.size(); i++) res.push_back(to_string(root->val) + "->" + rightpath[i]);
        return res;
    }               
};

提交后的结果如下:

方法二(对方法一优化)

其实可以不用额外创建一个res,另外还可以优化部分代码,使得整个程序变得更简洁明了。

class Solution{
public:
    vector<string> binaryTreePaths(TreeNode* root){
        if(root == NULL) return {};
        if(root->left == NULL && root->right == NULL) return {to_string(root->val)};

        vector<string> leftpath = binaryTreePaths(root->left);
        vector<string> rightpath = binaryTreePaths(root->right);

        leftpath.insert(leftpath.end(), rightpath.begin(), rightpath.end());
        for (auto &temp : leftpath){
            temp = to_string(root->val) + "->" + temp;
        }
        return leftpath;
    }
};

提交后的结果如下:

 

 

 

日积月累,与君共进,增增小结,未完待续。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值