https://leetcode.com/problems/binary-tree-inorder-traversal/
1.递归:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
inorder(root, result);
return result;
}
void inorder(TreeNode* root, vector<int>& tmp){
if(root==nullptr) return;
inorder(root->left, tmp);
tmp.push_back(root->val);
inorder(root->right, tmp);
}
};
2.非递归:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
inorder(root, s);
return result;
}
vector<int> result;//全局变量,存储打印的序列
vector<int> inorder(TreeNode* root, stack<TreeNode*> &s){
if(root==nullptr)
return result;
s.push(root);
while(!s.empty()){
TreeNode* tmp = s.top();
s.pop();
if(tmp->right!=nullptr || tmp->left!=nullptr){
if(tmp->right!=nullptr){
s.push(tmp->right);
tmp->right = nullptr;//切断右子树,防止重复压栈
}
s.push(tmp);
if(tmp->left!=nullptr){
s.push(tmp->left);
tmp->left = nullptr;//切断左子树,防止重复压栈
}
}
else{
result.push_back(tmp->val);
}
}
return result;
}
};
非递归精简版:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
TreeNode* p = root;
stack<TreeNode*> s;
while(!s.empty() || p!=nullptr){
if(p!=nullptr){
s.push(p);
p = p->left;
}
else{
p = s.top();
s.pop();
result.push_back(p->val);
p= p->right;
}
}
return result;
}
};