前序周遊
思路:前序周遊算法先通路樹的根節點,然後周遊左子樹,最後周遊右子樹。
解法1
1 /**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 * };
11 */
12 class Solution {
13 public:
14 vector<int> preorderTraversal(TreeNode* root)
15 {
16 if(!root) return {};
17 stack<TreeNode *> st;
18 vector<int> res;
19 TreeNode *p = root;
20 st.push(p);
21 while(!st.empty())
22 {
23 p = st.top();
24 st.pop();
25 res.push_back(p->val);
26
27 if(p->right) st.push(p->right);
28 if(p->left) st.push(p->left);
29 }
30 return res;
31 }
32 };
中序周遊
思路:中序周遊的算法先周遊左子樹,然後通路根節點,最後周遊右子樹。
1 /**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 * };
11 */
12 class Solution {
13 public:
14 vector<int> inorderTraversal(TreeNode* root)
15 {
16 if(!root) return {};
17
18 vector<int> res;
19 stack<TreeNode *> st;
20 TreeNode *p = root;
21
22 while(!st.empty() || p)
23 {
24 while(p)
25 {
26 st.push(p);
27 p = p->left;
28 }
29 p = st.top();
30 st.pop();
31 res.push_back(p->val);
32
33 p = p->right;
34 }
35 return res;
36 }
37 };