二叉樹前中後序非遞迴遍歷
阿新 • • 發佈:2020-09-02
/** * 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>res; public: void PreorderTraversal(TreeNode* root) { stack<TreeNode*>sstack; sstack.push(root); while( !sstack.empty() ) { TreeNode* temp=sstack.top(); sstack.pop(); res.push_back( temp->val ); if(temp->right) { sstack.push( temp->right ); } if(temp->left) { sstack.push( temp->left ); } } } vector<int> preorderTraversal(TreeNode* root) { if(root==NULL) { return {}; } PreorderTraversal(root); return res; } };
/** * 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> res; public: void InorderTraversal(TreeNode *root) { stack<TreeNode*>sstack; TreeNode*head=root; while( !sstack.empty()|| head!=NULL ) { if(head!=NULL) { sstack.push(head); head=head->left; } else { head=sstack.top(); sstack.pop(); res.push_back( head->val ); //cout<<head->val<<endl; head=head->right; } } } vector<int> inorderTraversal(TreeNode* root) { if(root==NULL) return {}; InorderTraversal(root); return res; } };
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int>res; stack<int>sstackres; public: void PostorderTraversal(TreeNode* root) { stack<TreeNode*>sstack; sstack.push(root); while( !sstack.empty() ) { TreeNode* temp=sstack.top(); sstack.pop(); sstackres.push(temp->val); if(temp->left) { sstack.push( temp->left ); } if(temp->right) { sstack.push( temp->right ); } } } vector<int> postorderTraversal(TreeNode* root) { if(root==NULL) return {}; PostorderTraversal(root); while( !sstackres.empty() ) { res.push_back( sstackres.top() ); sstackres.pop(); } return res; } };