94. 二叉樹的中序遍歷
遞歸版本
class Solution {
public:
vector<int>res;
vector<int> inorderTraversal(TreeNode* root) {
if(root==nullptr) return res;
inorderTraversal(root->left);
res.push_back(root->val);
inorderTraversal(root->right);
return res;
}
};
循環版本
因此其處理過程如下[1]:
對於任一結點P,
1)若其左孩子不爲空,則將P入棧並將P的左孩子置爲當前的P,然後對當前結點P再進行相同的處理;
2)若其左孩子爲空,則取棧頂元素並進行出棧操作,訪問該棧頂結點,然後將當前的P置爲棧頂結點的右孩子;
3)直到P爲NULL並且棧爲空則遍歷結束
class Solution {
public:
vector<int>res;
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*>s;
TreeNode *p = root;
while (p!=nullptr||!s.empty())
{
while (p)
{
s.push(p);
p = p->left;
}
if (!s.empty())
{
p = s.top();
s.pop();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};
144. 二叉樹的前序遍歷
非遞歸:
處理過程如下:
對於任一結點P:
1)訪問結點P,並將結點P入棧;
2)判斷結點P的左孩子是否爲空,若爲空,則取棧頂結點並進行出棧操作,並將棧頂結點的右孩子置爲當前的結點P,循環至1);若不爲空,則將P的左孩子置爲當前的結點P;
3)直到P爲NULL並且棧爲空,則遍歷結束。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*>s;
TreeNode* p = root;
while (p!=nullptr||!s.empty())
{
while (p != nullptr)
{
res.push_back(p->val);
s.push(p);
p = p->left;
}
if (!s.empty())
{
p=s.top();
s.pop();
p = p->right;
}
}
return res;
}
};
145. 二叉樹的後序遍歷
非遞歸:
[1]https://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html