前序遍历
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stack1;
if(root==NULL) return res;
stack1.push(root);
while(!stack1.empty())
{
TreeNode* topnum=stack1.top();
stack1.pop();
res.push_back(topnum->val);
if(topnum->right)
stack1.push(topnum->right);
if(topnum->left)
stack1.push(topnum->left);
}
return res;
}
中序遍历
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> stack1;
vector<int> res;
if(root==NULL) return res;
TreeNode* cur=root;
while(cur!=NULL||!stack1.empty())
{
while(cur!=NULL)
{
stack1.push(cur);
cur=cur->left;
}
cur=stack1.top();
stack1.pop();
res.push_back(cur->val);
cur=cur->right;
}
return res;
}
后续遍历
前序是根左右,后续是左右根,因此先生成根右左,再反转 得到左右根
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
stack<TreeNode*> stack1;
stack1.push(root);
while(!stack1.empty())
{
TreeNode* cur=stack1.top();
stack1.pop();
res.push_back(cur->val);
if(cur->left)
stack1.push(cur->left);
if(cur->right)
stack1.push(cur->right);
}
reverse(res.begin(),res.end());
return res;
}
102 二叉树层序遍历
429 N叉树层序遍历
589 N叉树前序遍历
590 N叉树后续遍历