您好,登錄后才能下訂單哦!
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.在葉子節(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: 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) { //葉子節(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<<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
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。