257. Binary Tree Paths

来源:互联网 发布:爆伤和黄字算法 编辑:程序博客网 时间:2024/06/06 07:01

问题描述

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();        //当穷尽一条路径,即找到叶后,把叶的父辈删掉    }};
原创粉丝点击