94. 二叉树的中序遍历
【遍历方法】
- 中序遍历其左子树;
- 访问根结点;
- 中序遍历其右子树。
解法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> 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 };