LeetCode —— 94. 二叉树的中序遍历
94. 二叉树的中序遍历
题目: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:
// void inorder(TreeNode* root, vector<int>& v)
// {
// if(root == nullptr)
// return;
// inorder(root->left, v);
// v.push_back(root->val);
// inorder(root->right, v);
// }
// vector<int> inorderTraversal(TreeNode* root) {
// vector<int> v;
// inorder(root, v);
// return v;
// }
// };// 方法二(非递归):先不访问根,压根,不管右节点,一直往左走,直到空,然后访问栈的根,然后去走根的右子树
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {stack<TreeNode*> st;vector<int> v;TreeNode* cur = root;while(cur != nullptr || !st.empty()){if(cur == nullptr){cur = st.top();v.push_back(cur->val);cur = cur->right;//右子树非空走的是右子树;右子树为空再次循环时再次取栈的topst.pop();}else{st.push(cur);cur = cur->left;}}return v;}
};