因为python不好写所以本题用cpp
- 二叉树的前序遍历
代码:
class Solution {
public:
vector preorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector result;
if (root == NULL) return result;
s.push(root);
while(!s.empty()){
TreeNode* node=s.top();
s.pop();
result.push_back(node->val);
if (node->right) s.push(node->right);
if (node->left) s.push(node->left);
}
return result;
}
};
- 二叉树的中序遍历
class Solution {
public:
vector inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector result;
TreeNode* cur=root;
while(cur!=NULL || !s.empty()){
if (cur!=NULL){
s.push(cur);
cur=cur->left;
}else{
cur=s.top();
s.pop();
result.push_back(cur->val);
cur=cur->right;
}
}
return result;
}
};
woc,就是快啊cpp
- 二叉树的后序遍历
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
树中节点的数目在范围 [0, 100] 内
-100 <= Node.val <= 100
代码:
class Solution {
public:
vector postorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector result;
if (root==NULL) return result;
s.push(root);
while(!s.empty()){
TreeNode* node=s.top();
s.pop();
result.push_back(node->val);
if(node->left) s.push(node->left);
if(node->right) s.push(node->right);
}
reverse(result.begin(),result.end());
return result;
}
};