【LeetCode】257. Binary Tree Paths

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

 

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

深度优先遍历,每遇到叶节点,将栈中路径记录下来,最后将所有路径转成所需格式

复制代码
/**
 * 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> path;
        if(root == NULL)
            return path;
        vector<vector<int> > pathv;    
        unordered_map<TreeNode*, bool> visited;
        stack<TreeNode*> stk;
        stk.push(root);
        visited[root] = true;
        if(root->left == NULL && root->right == NULL)
            save(pathv, stk);
        while(!stk.empty())
        {
            TreeNode* top = stk.top();
            if(top->left && visited[top->left] == false)
            {
                stk.push(top->left);
                visited[top->left] = true;
                if(top->left->left == NULL && top->left->right == NULL)
                    save(pathv, stk);
                continue;
            }
            if(top->right && visited[top->right] == false)
            {
                stk.push(top->right);
                visited[top->right] = true;
                if(top->right->left == NULL && top->right->right == NULL)
                    save(pathv, stk);
                continue;
            }
            stk.pop();
        }
        return convert(pathv);
    }
    void save(vector<vector<int> >& pathv, stack<TreeNode*> stk)
    {
        vector<int> cur;
        while(!stk.empty())
        {
            TreeNode* top = stk.top();
            cur.push_back(top->val);
            stk.pop();
        }
        reverse(cur.begin(), cur.end());
        pathv.push_back(cur);
    }
    vector<string> convert(vector<vector<int> >& pathv)
    {
        vector<string> path;
        for(int i = 0; i < pathv.size(); i ++)
        {
            string cur;
            cur += to_string(pathv[i][0]);
            for(int j = 1; j < pathv[i].size(); j ++)
            {
                cur += "->";
                cur += to_string(pathv[i][j]);
            }
            path.push_back(cur);
        }
        return path;
    }
};
复制代码

posted @   陆草纯  阅读(2235)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示