赞
踩
- class Solution {
- public:
- void preorder(TreeNode* root, vector<int> &res){
- if(root == nullptr){
- return;
- }
- res.push_back(root->val);
- preorder(root->left, res);
- preorder(root->right, res);
- }
- vector<int> preorderTraversal(TreeNode* root) {
- vector<int> res;
- preorder(root, res);
- return res;
- }
- };
- class Solution {
- public:
- vector<int> preorderTraversal(TreeNode* root) {
- vector<int> res;
- if(root == nullptr){
- return res;
- }
- stack<TreeNode*> stk;
- TreeNode* node = root;
- while(!stk.empty() || node != nullptr){
- while(node != nullptr){
- stk.push(node);
- res.push_back(node->val);
- node = node->left;
- }
- node = stk.top();
- stk.pop();
- node = node->right;
- }
- return res;
- }
- };
- class Solution {
- public:
- void postorder(TreeNode* root, vector<int>& res){
- if(root == nullptr){
- return;
- }
- postorder(root->left, res);
- res.push_back(root->val);
- postorder(root->right, res);
-
- }
- vector<int> inorderTraversal(TreeNode* root) {
- vector<int> res;
- postorder(root, res);
- return res;
- }
- };
- class Solution {
- public:
- vector<int> inorderTraversal(TreeNode* root) {
- vector<int> res;
- if(root == nullptr){
- return res;
- }
- stack<TreeNode*> stk;
- TreeNode* node = root;
- while(!stk.empty() || node != nullptr){
- while(node != nullptr){
- stk.push(node);
- node = node->left;
- }
- node = stk.top();
- res.push_back(node->val);
- stk.pop();
- node = node->right;
- }
- return res;
- }
- };
时间复杂度:O(N)每个结点会遍历一次且只遍历一次
空间复杂度:O(N)栈至多会存放所有树节点
- class Solution {
- public:
- void postorder(TreeNode* root, vector<int>& res){
- if(root == nullptr){
- return;
- }
- postorder(root->left, res);
- postorder(root->right, res);
- res.push_back(root->val);
- }
- vector<int> postorderTraversal(TreeNode* root) {
- vector<int> res;
- postorder(root, res);
- return res;
- }
- };
- class Solution {
- public:
- vector<int> postorderTraversal(TreeNode* root) {
- vector<int> res;
- if(root == nullptr){
- return res;
- }
- stack<TreeNode*> stk;
- TreeNode * prev = nullptr;
- while(!stk.empty() || root != nullptr){
- while(root != nullptr){
- stk.push(root);
- root = root->left;
- }
- root = stk.top();
- stk.pop();
- if(root->right == nullptr || root->right == prev){
- res.push_back(root->val);
- prev = root;
- root = nullptr;
- }else{
- stk.push(root);
- root = root->right;
- }
- }
- return res;
- }
- };
从根节点开始遍历,并将根节点入栈,再遍历他的左子树,并依次入栈,直到该结点没有左子树。判断这个结点是否有右子树,如果没有,则将该结点弹出栈,并记录结点值。如果有则继续从他的右子树进行遍历,同时记录该结点的右子树是否遍历过,如果遍历过,则弹栈并记录结点值。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。