[leetcode]: 257. Binary Tree Paths

来源:互联网 发布:玉环网络安全教育平台 编辑:程序博客网 时间:2024/05/22 05:35

1.题目

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”]
给一棵二叉树,返回所有根节点到叶子节点的路径。

2.分析

本题考察二叉树的遍历。遍历过程中记录元素的顺序,遍历到底部叶节点则完成一条路径。

3.代码

深度优先遍历,非递归

class Solution {public:    vector<string> binaryTreePaths(TreeNode* root) {        vector<string> ans;        if (root == NULL)            return ans;        stack<TreeNode*> nodes;        stack<string> path;        nodes.push(root);        path.push(to_string(root->val));        while (!nodes.empty()) {            TreeNode* node = nodes.top();            nodes.pop();            string curpath = path.top();            path.pop();            if (node->left == NULL&&node->right == NULL)                ans.push_back(curpath);            if (node->left) {                nodes.push(node->left);                path.push(curpath + "->" + to_string(node->left->val));            }            if (node->right) {                nodes.push(node->right);                path.push(curpath + "->" + to_string(node->right->val));            }        }        return ans;    }};

DFS,递归

void getTreePath(TreeNode* root,string curPath, vector<string>& ans) {    if (root->left == NULL && root->right == NULL)        ans.push_back(curPath);    if (root -> left)        getTreePath(root->left, curPath + "->" + to_string(root->left->val), ans);    if (root->right)        getTreePath(root->right, curPath + "->" + to_string(root->right->val), ans);}vector<string> binaryTreePaths(TreeNode* root) {    vector<string> ans;    if (root == NULL)        return ans;    getTreePath(root, to_string(root->val), ans);    return ans;}
原创粉丝点击