前序遍历:先访问跟结点,然后遍历左子树,最后遍历右子树。即“根左右”。
实现代码:
class Solution { public: vector<int> preorderTraversal(TreeNode *root) { if (root==NULL) { return vector<int>(); } vector<int> result; stack<TreeNode *> treeStack; treeStack.push(root); while (!treeStack.empty()) { TreeNode *temp = treeStack.top(); result.push_back(temp->val); treeStack.pop(); if (temp->right!=NULL) { treeStack.push(temp->right); } if (temp->left!=NULL) { treeStack.push(temp->left); } } return result; } };
实现代码:
</pre><pre name="code" class="cpp">class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode *> stk; while(root||!stk.empty()) { while(root!=NULL) { stk.push(root); root=root->left; } TreeNode *temp=stk.top(); stk.pop(); res.push_back(temp->val); root=temp->right; } return res; } };
实现代码:
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> result; if(root==NULL) return result; stack<TreeNode*> tr; tr.push(root); while(!tr.empty()) { TreeNode* temp=tr.top(); tr.pop(); result.push_back(temp->val); if(temp->left) tr.push(temp->left); if(temp->right) tr.push(temp->right); } reverse(result.begin(),result.end()); return result; } };
原文地址:http://blog.csdn.net/wolongdede/article/details/44921297