温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

leetCode 257. Binary Tree Paths 二叉树路径

发布时间:2020-07-03 16:01:55 来源:网络 阅读:898 作者:313119992 栏目:编程语言

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

思路:

1.采用二叉树的后序遍历非递归版

2.在叶子节点的时候处理字符串

代码如下:

/**
 * 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;
        vector<TreeNode *> temp;
        stack<TreeNode *> s;
        
        TreeNode *p,*q;
        q = NULL;
        p = root;
        
        while(p != NULL || s.size() > 0)
        {
            while( p != NULL)
            {
                s.push(p);
                p = p->left;
            }
            if(s.size() > 0)
            {
                p = s.top();
                
                if( NULL == p->left && NULL == p->right)
                {
                    //叶子节点已经找到,现在栈里面的元素都是路径上的点
                    //将栈中元素吐出放入vector中。
                    int len = s.size();
                    for(int i = 0; i < len; i++)
                    {
                        temp.push_back(s.top());
                        s.pop();
                    }
                    
                    string strTemp = "";
                    for(int i = temp.size() - 1; i >= 0;i--)
                    {
                        stringstream ss;
                        ss<<temp[i]->val;
                        strTemp += ss.str();
                        if(i >= 1)
                        {
                            strTemp.append("->");
                        }
                    }
                    result.push_back(strTemp);
                    
                    for(int i = temp.size() - 1; i >= 0;i--)
                    {
                        s.push(temp[i]);
                    }
                    temp.clear();
                    
                }
                
                if( (NULL == p->right || p->right == q) )
                {
                    q = p;
                    s.pop();
                    p = NULL;
                }
                else
                    p = p->right;
            }
        }
        
        return result;
    }
};

2016-08-07 01:47:24

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI