257. Binary Tree Paths
祁連網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)建站,祁連網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為祁連上千余家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)營銷網(wǎng)站建設(shè)要多少錢,請找那個(gè)售后服務(wù)好的祁連做網(wǎng)站的公司定做!
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.在葉子節(jié)點(diǎn)的時(shí)候處理字符串
代碼如下:
/** * 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: vectorbinaryTreePaths(TreeNode* root) { vector result; vector temp; stack 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) { //葉子節(jié)點(diǎn)已經(jīng)找到,現(xiàn)在棧里面的元素都是路徑上的點(diǎn) //將棧中元素吐出放入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< 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