# 【LeetCode】94. 二叉树的中序遍历

class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
vector<int> left;
vector<int> right;
if (root != NULL) {
left = inorderTraversal(root->left);
res.insert(res.end(), left.begin(), left.end());
res.push_back(root->val);
right = inorderTraversal(root->right);
res.insert(res.end(), right.begin(), right.end());
}
return res;
}
};

class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if (root == NULL) {
return res;
}
stack<TreeNode*> Stack;
set<TreeNode*> visited;
Stack.push(root);//压入头结点
TreeNode* node;//暂存
while (!Stack.empty()) {
node = Stack.top();
//若左孩子存在且没有被访问过，压栈
while (node->left != NULL && visited.find(node->left) == visited.end()) {
Stack.push(node->left);
node = node->left;
}
//访问节点并弹出
res.push_back(node->val);
visited.insert(node);
Stack.pop();
//若右孩子存在(右孩子不会重复访问)
if (node->right != NULL) {
Stack.push(node->right);
}
}
return res;
}
};

07-14 114

05-21 24

05-23 23

06-21 356

05-04 908

01-05 375

10-11 400

08-13 93

12-10 37

08-26 7638

11-02 19

01-05 101

02-17 4269

07-08 198

03-12 29

06-04 75

11-28 156

08-25 647

03-09 80

09-23 335

#### Leetcode 105. 从前序与中序遍历序列构造二叉树

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客