【144】二叉树的前序遍历
1、递归法:
class Solution { public: void preorder(TreeNode* root, vector&res){ if(root == nullptr){ return; } res.push_back(root->val); preorder(root->left, res); preorder(root->right, res); } vector preorderTraversal(TreeNode* root) { vector res; preorder(root, res); return res; } };
2、迭代法
class Solution { public: vectorpreorderTraversal(TreeNode* root) { vector res; if(root == nullptr){ return res; } stack 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; } };
【94】二叉树的中序遍历
1、递归法
class Solution { public: void postorder(TreeNode* root, vector& res){ if(root == nullptr){ return; } postorder(root->left, res); res.push_back(root->val); postorder(root->right, res); } vector inorderTraversal(TreeNode* root) { vector res; postorder(root, res); return res; } };
2、迭代法
class Solution { public: vectorinorderTraversal(TreeNode* root) { vector res; if(root == nullptr){ return res; } stack 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)栈至多会存放所有树节点
【145】二叉树的后序遍历
1、递归法
class Solution { public: void postorder(TreeNode* root, vector& res){ if(root == nullptr){ return; } postorder(root->left, res); postorder(root->right, res); res.push_back(root->val); } vector postorderTraversal(TreeNode* root) { vector res; postorder(root, res); return res; } };
2、迭代法
class Solution { public: vectorpostorderTraversal(TreeNode* root) { vector res; if(root == nullptr){ return res; } stack 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; } };
思路:
从根节点开始遍历,并将根节点入栈,再遍历他的左子树,并依次入栈,直到该结点没有左子树。判断这个结点是否有右子树,如果没有,则将该结点弹出栈,并记录结点值。如果有则继续从他的右子树进行遍历,同时记录该结点的右子树是否遍历过,如果遍历过,则弹栈并记录结点值。
还没有评论,来说两句吧...