【資料結構】二叉樹專題
阿新 • • 發佈:2022-04-15
LeetCode 94. 二叉樹的中序遍歷
遞迴寫法
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> res; void dfs(TreeNode* root) { if(!root) return; dfs(root->left); res.push_back(root->val); dfs(root->right); } vector<int> inorderTraversal(TreeNode* root) { dfs(root); return res; } }; 作者:Once. 連結:https://www.acwing.com/activity/content/code/content/3201627/ 來源:AcWing 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。
非遞迴寫法(利用棧,固定套路,要求背會)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; // 定義答案陣列 stack<TreeNode*> stk; // 定義棧 while(root || stk.size()) // 噹噹前結點非空或棧非空時 { while(root) // 噹噹前結點不空時 { stk.push(root); // 將當前結點入棧 root = root->left; // 當前結點走到其左兒子的位置 } root = stk.top(); // 將棧頂元素的值取出 stk.pop(); // 將棧頂元素彈出 res.push_back(root->val); // 遍歷當前點 root = root->right; // 遍歷完之後走到當前結點的右兒子 } return res; // 返回答案陣列 } }; 作者:Once. 連結:https://www.acwing.com/activity/content/code/content/3201627/ 來源:AcWing 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。