代碼隨想錄二刷 |二叉樹 |二叉樹的中序遍歷
- 題目描述
- 解題思路
- 代碼實現
- 迭代法
- 遞歸法
題目描述
94.二叉樹的中序遍歷
給定一個二叉樹的根節點 root ,返回 它的 中序 遍歷 。
示例 1:
輸入:root = [1,null,2,3]
輸出:[1,3,2]
示例 2:
輸入:root = []
輸出:[]
示例 3:
輸入:root = [1]
輸出:[1]
提示:
- 樹中節點數目在范圍 [0, 100] 內
- -100 <= Node.val <= 100
解題思路
在處理的節點放入棧之后,緊接著放入一個空指針作為標記
代碼實現
迭代法
class Solution {
public:void traversal(TreeNode* cur, vector<int>& vec) {if (cur == NULL) return;traversal(cur->left, vec);vec.push_back(cur->val);traversal(cur->right, vec);}vector<int> inorderTraversal(TreeNode* root) {vector<int> result;traversal(root, result);return result;}
};
遞歸法
// 中序遍歷:左中右
// 入棧順序:右中左
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {vector<int> result;stack<TreeNode*> st;if (root != NULL) st.push(root);while (!st.empty()) {TreeNode* node = st.top();if (node != NULL) {st.pop();if (node->right) st.push(node->right);st.push(node);st.push(NULL);if (node->left) st.push(node->left);} else {st.pop();node = st.top();st.pop();result.push_back(node->val);}}return result;}
};