本文主要包括利用遞歸和迭代的方法實現二叉樹的前序、中序、後序遍歷!
144. 二叉樹的前序遍歷
給定一個二叉樹,返回它的 前序遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,2,3]
解題思路
1.1 樹的前序遍歷–非遞歸方法(棧)
- 因爲先訪問根節點,所以直接將root的val放入答案(ans)容器
- 利用stack來儲存root。
- 當左子樹遍歷完後,取出root接着遍歷右子樹。
C++實現:
/**
* 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) {
std::stack<TreeNode*> stack;
vector<int> ans;
while(root != NULL || !stack.empty()) {
while(root != NULL) {
stack.push(root);
ans.push_back(root->val);
root = root->left;
}
root = stack.top();
stack.pop();
root = root->right;
}
return ans;
}
};
Python實現:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root is None:
return []
stack,res=[root,],[]
while stack:
root = stack.pop()
if root is not None:
res.append(root.val)
if root.right is not None:
stack.append(root.right)
if root.left is not None:
stack.append(root.left)
return res
1.2 遞歸的思想
C++實現
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
if(root != NULL){
ans.push_back(root -> val);
preorderTraversal(root -> left);
preorderTraversal(root -> right);
}
return ans;
}
};
Python實現:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def preorder(root):
if not root:return
res.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return res
94. 二叉樹的中序遍歷
給定一個二叉樹,返回它的中序遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,2,3]
解題思路
2.1 利用棧的思想
C++實現:
/**
* 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) {
vector<int> res;
stack<TreeNode*> stack;
//s.push(root);
while(root || s.size() > 0){
while(root){
stack.push(root);
root = root->left;
}
root = stack.top();
stack.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
};
python實現:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
stack = []
while root or stack:
# 把左子樹壓入棧中
while root:
stack.append(root)
root = root.left
# 輸出 棧頂元素
root = stack.pop()
res.append(root.val)
# 遍歷右子樹
root = root.right
return res
2.2 遞歸的思想
C++實現:
/**
* 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> ans;
vector<int> inorderTraversal(TreeNode* root) {
if(root != NULL){
inorderTraversal(root -> left);
ans.push_back(root -> val);
inorderTraversal(root -> right);
}
return ans;
}
};
Python實現:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def inorder(root):
if not root:return
inorder(root.left)
res.append(root.val)
inorder(root.right)
inorder(root)
return res
145. 二叉樹的後序遍歷
給定一個二叉樹,返回它的 後序 遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,2,3]
解題思路
3.1 利用迭代的思想(棧)
C++實現:
- 先遍歷左節點直到左節點爲null。
- 開始遍歷右節點,若該右節點有左節點,優先遍歷左節點。
- 使用rightchild來記錄右節點是否已被遍歷過。若是:則說明以該點爲根的子樹已被遍歷,輸出根節點。若否:就開始遍歷右節點,回到第二步。
/**
* 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) {
vector<int> ans;
stack<TreeNode*> stk;
TreeNode* cur = root;
TreeNode* rightchild = NULL;
while(cur || !stk.empty()){
while(cur != NULL){
stk.push(cur);
cur = cur -> left;
}
cur = stk.top();
if(!cur -> right|| rightchild == cur -> right){
ans.push_back(cur -> val);
stk.pop();
rightchild = cur;
cur = NULL;
}
else{
rightchild = NULL;
cur = cur -> right;
}
}
return ans;
}
};
Python實現:
-
從根節點開始依次迭代,彈出棧頂元素輸出到輸出列表中,然後依次壓入它的所有孩子節點,按照從上到下、從左至右的順序依次壓入棧中。
-
因爲深度優先搜索後序遍歷的順序是從下到上、從左至右,所以需要將輸出列表逆序輸出。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if root is None:
return []
stack, output = [root, ], []
while stack:
root = stack.pop()
output.append(root.val)
if root.left is not None:
stack.append(root.left)
if root.right is not None:
stack.append(root.right)
return output[::-1]
3.2 遞歸的思想
C++實現:
/**
* 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> ans;
vector<int> postorderTraversal(TreeNode* root) {
if(root != NULL){
postorderTraversal(root->left);
postorderTraversal(root->right);
ans.push_back(root -> val);
}
return ans;
}
};
Python實現:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def postorder(root):
if not root:
return
postorder(root.left)
postorder(root.right)
res.append(root.val)
postorder(root)
return res