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

思路分析

这道题是利用深度优先算法,把每个叶子的路径记录下来。首先创建一个储存父辈值的数组paths。在前序中,存入所遇到的节点的值。当遇到叶子时,不需要存入自己的值,只需要取出paths的值,形成路径链,存入结果中。然后访问完当前叶子,返回上一层递归。父辈的值,在后序中pop出paths.
如立体。paths的值为{1},{1,2},{1,2,5},{1},{1,3},{1},{}

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result={};    //存储每一个叶的路径
        if(root==NULL) {
            return result;
        }
        DFS(root,result);
        return result;
    }
    vector<int> paths={};                       //储存叶的父辈
    void DFS(TreeNode* root, vector<string>& result) {
        if(root->left==NULL&&root->right==NULL) {  //当遇到叶时,就把他的父辈取出,形成路径
            string temp="";
            for(int i=0;i<paths.size();i++) {
                temp=temp+to_string (paths[i]);
                temp+="->";
            }
            temp=temp+to_string ((root->val));  //最后加上自己
            result.push_back(temp);
            return;
        }
        paths.push_back(root->val);      //把非叶的节点加到父辈paths数组
        if(root->left!=NULL) {
            DFS(root->left,result);
        }
        if(root->right!=NULL) {
            DFS(root->right,result);
        }
        paths.pop_back();        //当穷尽一条路径,即找到叶后,把叶的父辈删掉
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值