国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Leetcode 144. Binary Tree Preorder Traversal

2019-11-11 06:21:22
字體:
供稿:網(wǎng)友

Given a binary tree, return the PReorder traversal of its nodes’ values.

For example: Given binary tree {1,#,2,3},

1 / 2 / 3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

s思路: 1. pre-order之前有遇到過:先根,再左,后右。recursive確實容易。iterative稍微比in-order麻煩一些,需要用stack,關(guān)鍵是使用兩個指針pnow和pre,防止做回頭路! 2. 這個pre和pnow的關(guān)系是:pnow訪問了左邊,移動到右邊之前,pre被賦值為pnow;當(dāng)pnow訪問了右邊,移動到上層之前,pre被賦值為pnow。

//方法1:recursive: pre-orderclass Solution {public: void helper(vector<int>&res,TreeNode* root){ if(!root) return; res.push_back(root->val);//root helper(res,root->left);//left helper(res,root->right);//right } vector<int> preorderTraversal(TreeNode* root) { // vector<int> res; helper(res,root); return res; }};//方法2:iterative: pre-order;stack;pre+pnowclass Solution {public: vector<int> preorderTraversal(TreeNode* root) { // vector<int> res; stack<TreeNode*> ss; TreeNode* pnow=root,*pre=NULL; while(!ss.empty()||pnow){ while(pnow){ res.push_back(pnow->val); ss.push(pnow); pnow=pnow->left; } pnow=ss.top(); if(pnow->right&&pnow->right!=pre){ pnow=pnow->right; }else{ pre=pnow; ss.pop(); pnow=NULL; } } return res; }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 山东省| 丹江口市| 赣州市| 辰溪县| 洛浦县| 宽甸| 柘荣县| 同仁县| 万州区| 沙湾县| 冷水江市| 麟游县| 秀山| 册亨县| 搜索| 陆良县| 无棣县| 江城| 鄂托克前旗| 若尔盖县| 锦屏县| 仁寿县| 清河县| 赣州市| 光泽县| 浠水县| 祁东县| 博野县| 米林县| 山阳县| 寿阳县| 汾西县| 汽车| 乐山市| 沅陵县| 白河县| 额敏县| 墨玉县| 安宁市| 万源市| 栾川县|