棧和遞歸的關系 144:Binary Tree Preorder Traversal

前序遍歷:根左右

//用棧來實現非遞歸解法
/*
** 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<int> preorderTraversal(TreeNode* root) {vector<int> res;if(root == NULL)return res;stack<TreeNode*> stack;stack.push(root);while(!stack.empty()){TreeNode* c = stack.top();stack.pop();res.push_back(c->val);if(c->right)stack.push(c->right);if(c->left)stack.push(c->left);}return res;} };
//遞歸解法,注意res是全局的,要放在遍歷函數外面
/*
** 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<int> res;vector<int> preorderTraversal(TreeNode* root) {if(root){res.push_back(root->val);preorderTraversal(root->left);preorderTraversal(root->right);}return res;} };

中序遍歷:左根右

/*** 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<int> inorderTraversal(TreeNode* root) {stack<TreeNode*> st;vector<int> res;if(root == NULL) return res;  //若根節點為空則返回空TreeNode* p = root;while(p || !st.empty()){while(p){//先將根節點入棧,再將它所有的左節點入棧
                st.push(p);p = p->left;   }p = st.top();st.pop();res.push_back(p->val);p = p->right;}return res;}
};

?后序遍歷:左右根

可以使其遍歷順序為根左右,然后逆序插入vector中,即每次在vector的頭部插入結點值。在壓入棧時先壓入右結點再壓入左結點則在出棧時就是先左后右了。

//解法一
/*
** 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<int> postorderTraversal(TreeNode* root) {if(!root) return {};vector<int> res;stack<TreeNode*> s{{root}};while(!s.empty()){TreeNode* t = s.top();s.pop();res.insert(res.begin(), t->val);if(t->left) s.push(t->left);if(t->right) s.push(t->right);}return res;} };

解法二:關鍵是判斷當前這個結點:

1)它如果有左右結點是否已經入棧,若沒有入棧則先將它的右結點入棧,再左結點入棧;如果它的左右結點已經入棧,則這個結點就可以直接加入容器vector里了。

2)如果它是葉子結點(沒有左右結點),則直接加入vector中。

/*** 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<int> postorderTraversal(TreeNode* root) {if(!root) return {};vector<int> res;stack<TreeNode*> s{{root}};TreeNode* head = root;   //head初始化while(!s.empty()){TreeNode* t = s.top();if((!t->left && !t->right) || t->left==head || t->right==head){//當t為葉子結點 或t的左結點或右結點為head,即已經入棧了res.push_back(t->val);s.pop();head = t;}else{if(t->right) s.push(t->right);if(t->left) s.push(t->left);}}return res;}
};

?

leetcode已經分別定義了類NestedInteger中的三個函數:

1)isInteger():若當前這個NestedInteger是單個整數返回true;

2)getInteger():返回當前這個單個的整數;

3)getList():返回當前這個列表。

/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* class NestedInteger {*   public:*     // Return true if this NestedInteger holds a single integer, rather than a nested list.*     bool isInteger() const;**     // Return the single integer that this NestedInteger holds, if it holds a single integer*     // The result is undefined if this NestedInteger holds a nested list*     int getInteger() const;**     // Return the nested list that this NestedInteger holds, if it holds a nested list*     // The result is undefined if this NestedInteger holds a single integer*     const vector<NestedInteger> &getList() const;* };*/
class NestedIterator {
public:stack<NestedInteger> s;NestedIterator(vector<NestedInteger> &nestedList) {for(int i=nestedList.size()-1; i>=0; i--)//倒序插入 是為了彈出時是正序的
            s.push(nestedList[i]);}int next() {//返回下一項的值NestedInteger t = s.top();s.pop();return t.getInteger();  //獲取對應整數
        }bool hasNext() {//若下一項有值,返回truewhile(!s.empty()){NestedInteger t = s.top();if(t.isInteger())return true;   //若下一個數是單個整數,返回true
            s.pop();//若下一個數是一個列表,使用getList()得到列表的每個整數倒序插入到棧中for(int i=t.getList().size()-1; i>=0; i--)s.push(t.getList()[i]);}return false;}
};/*** Your NestedIterator object will be instantiated and called as such:* NestedIterator i(nestedList);* while (i.hasNext()) cout << i.next();*/

?

轉載于:https://www.cnblogs.com/Bella2017/p/10279952.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395427.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395427.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395427.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

運行級別

ls -l /usr/lib/system/runlevel*target &#xff08;查看運行級別&#xff09;Linux系統有7個運行級別(runlevel)運行級別0&#xff1a;系統停機狀態&#xff0c;系統默認運行級別不能設為0&#xff0c;否則不能正常啟動運行級別1&#xff1a;單用戶工作狀態&#xff0c;roo…

微信sdk swift版_使用Swift 4的iOS版Google Maps SDK終極指南

微信sdk swift版by Dejan Atanasov通過Dejan Atanasov 使用Swift 4的iOS版Google Maps SDK終極指南 (Your ultimate guide to the Google Maps SDK on iOS, using Swift 4) Many iOS apps use Google Maps. This is a very common feature, so I have decided to prepare an u…

精確覆蓋DLX算法模板

代碼 struct DLX {int n,id;int L[maxn],R[maxn],U[maxn],D[maxn];int C[maxn],S[maxn],loc[maxn][2];void init(int nn0) //傳列長{nnn;for(int i0;i<n;i) U[i]D[i]i,L[i]i-1,R[i]i1;L[0]n; R[n]0;idn;memset(S,0,sizeof(S));}void AddRow(int x,int col,int A[]) //傳入參…

android 代碼布局設置wrap_content,android ScrollView布局(wrap_content,最大大小)

我最后編寫了自己的類,擴展了ScrollView既然你問……這是代碼.可能不是最干凈但它做我想要的.請注意,它期望在創建視圖時設置layout_weight,并且不應在父LinearLayout中設置weigthSum,否則你會得到有趣的東西(因為這個的權重從原始值變為0,具體取決于大小ScrollView的內容)首先…

ABAP數據類型

數據類型表&#xff1a; 類型縮寫 類型 默認長度 允許長度 初始值 描述 C 文本型 1 Space 字符串數據,如Program D 日期型 8 8 00000000 日期數據,格式為YYYYMMDD F 浮點型 8 8 0 浮點數 I 整型 4 10 0 帶正負符號的整數 N 數值型 1 31 00……

cocos2d-x C++ 原始工程引擎運行機制解析

新建一個工程&#xff0c;相信感興趣的同學都想知道cocos引擎都是如何運行的 想知道是如何運行的&#xff0c;看懂四個文件即可 話不多說&#xff0c;上代碼&#xff1a; 1、首先解釋 AppDelegate.h 1 #ifndef _APP_DELEGATE_H_2 #define _APP_DELEGATE_H_3 4 #include "…

web高德maker動畫_Web Maker —我如何構建一個快速的離線前端游樂場

web高德maker動畫by kushagra gour由kushagra gour Web Maker —我如何構建一個快速的離線前端游樂場 (Web Maker — How I built a fast, offline front-end playground) Web Maker is a Chrome extension that gives you a blazing fast and offline front-end playground —…

時間小知識對于時間轉換可能有幫助

那么UTC與世界各地的時間應如何換算呢?它是將全世界分為24個時區&#xff0c;地球的東、西經各180(共360)被24個時區平分&#xff0c;每個時區各占15。以經度0(即本初子午線)為基準&#xff0c;東經730′與西經730′之間的區域為零時區&#xff1b;東經和西經的730′與2230′之…

JS——實現短信驗證碼的倒計時功能(沒有驗證碼,只有倒計時)

1、功能描述 當用戶想要獲取驗證碼時&#xff0c;就點擊 免費獲取驗證碼 &#xff0c;然后開始倒計時&#xff0c;倒計時期間按鈕文字為剩余時間x秒&#xff0c;且不可按狀態&#xff0c;倒計時結束后&#xff0c;按鈕更改為點擊重新發送。 2、分析 必須用到定時器。按鈕點擊后…

華為OV小米鴻蒙,華為鴻蒙開源,小米OV們會采用嗎?

華為曾一直聲言不會進入電視市場,由此其他國產電視企業才會采用華為的可見企業是非常擔憂同業競爭關系的,而在智能手機市場,華為毫無疑問與其他國產手機企業都是競爭對手,更何況就在2019年下半年和2020年上半年華為在國內手機市場的份額超過四成直逼五成,其他國產手機企業被壓得…

第22天:如何使用OpenAI Gym和Universe構建AI游戲機器人

by Harini Janakiraman通過哈里尼賈納基拉曼 第22天&#xff1a;如何使用OpenAI Gym和Universe構建AI游戲機器人 (Day 22: How to build an AI Game Bot using OpenAI Gym and Universe) Let’s face it, AI is everywhere. A face-off battle is unfolding between Elon Musk…

軟件測試基礎理論(總結)

1&#xff0e; 軟件的三個要素&#xff1a;程序&#xff08;實行特定功能的代碼&#xff09; 文檔&#xff08;支持代碼運行&#xff09; 數據&#xff08;支持程序運行一切有關&#xff09; 2&#xff0e; 軟件的產品質量 指的是&#xff1f; 1&#xff09;質量是指實體特性…

android studio 7200u,#本站首曬# 多圖殺貓 華為MateBook X上手體驗

#本站首曬# 多圖殺貓 華為MateBook X上手體驗2017-06-09 18:45:4437點贊33收藏78評論前幾天華為開了個發布會&#xff0c;帶來了三款筆記本電腦&#xff0c;有幸在第一時間借到了MateBook X&#xff0c;現在就來來做一個簡單的上手&#xff0c;稍晚一些再跟大家詳細聊聊使用起來…

svn強制解鎖的幾種做法

標簽&#xff1a; svn強制解鎖2013-12-16 17:40 12953人閱讀 評論(0) 收藏 舉報分類&#xff1a;SoftwareProject&#xff08;23&#xff09; 版權聲明&#xff1a;本文為博主原創文章&#xff0c;未經博主允許不得轉載。 作者&#xff1a;朱金燦 來源&#xff1a;http://blog.…

數據結構和算法練習網站_視頻和練習介紹了10種常見數據結構

數據結構和算法練習網站“Bad programmers worry about the code. Good programmers worry about data structures and their relationships.” — Linus Torvalds, creator of Linux“糟糕的程序員擔心代碼。 好的程序員擔心數據結構及其關系。” — Linux的創建者Linus Torva…

突然討厭做前端,討厭代碼_有關互聯網用戶最討厭的廣告類型的新數據

突然討厭做前端,討厭代碼You know that feeling when you’re scrolling through a blog post and then — BAM! — one of those “Sign up for our newsletter” modals pops up?當您滾動瀏覽博客文章&#xff0c;然后-BAM時&#xff0c;您就會知道這種感覺。 -彈出“注冊我…

iOS設計模式-生成器

定義&#xff1a;將一個產品的內部表象與產品的生成過程分割開來&#xff0c;從而可以使一個建造過程生成具有不同的內部表象的產品對象。 類型&#xff1a;對象創建 類圖&#xff1a; #import <Foundation/Foundation.h> interface Character : NSObject property(nonat…

《Android 應用案例開發大全(第二版)》——導讀

本節書摘來自異步社區《Android 應用案例開發大全&#xff08;第二版&#xff09;》一書中的目錄 &#xff0c;作者 吳亞峰 , 于復興 , 杜化美&#xff0c;更多章節內容可以訪問云棲社區“異步社區”公眾號查看 目 錄 第1章 初識廬山真面目——Android簡介 1.1 Android的誕生 1…

模塊--sys模塊

sys模塊是與python解釋器交互的一個接口 import sys sys.path #python解釋器找模塊的環境變量import sys print(sys.path)結果:[H:\\王文靜\\python\\4練習\\課堂練習, H:\\王文靜\\python, C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\pyth…

匿名方法

與前面的可空類型是一樣的&#xff0c;匿名方法也是C# 2.0里面提出來的。 1 匿名方法 1.1 什么是匿名方法&#xff1f; 顧名思義&#xff0c;就是沒有名稱的方法&#xff0c;因為沒有名稱&#xff0c;匿名方法只能在函數定義&#xff08;匿名方法是把方法的實現和定義嵌套在了一…