首页 > 其他 > 详细

leetCode 257. Binary Tree Paths 二叉树路径

时间:2016-08-07 09:44:28      阅读:192      评论:0      收藏:0      [点我收藏+]

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

本文出自 “做最好的自己” 博客,请务必保留此出处http://qiaopeng688.blog.51cto.com/3572484/1835177

leetCode 257. Binary Tree Paths 二叉树路径

原文:http://qiaopeng688.blog.51cto.com/3572484/1835177

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!