/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
bfs :
void bfs(TreeNode *root) { if(root==NULL) return; queue<TreeNode *> x; TreeNode *t; x.push(root); while(!x.empty()){ t = x.front(); if(t->left!=NULL) x.push(t->left); if(t->right!=NULL) x.push(x->right); // do something x.pop(); } }递归dfs:
void dfs(TreeNode *root) { if(root==NULL) return; if(root->left != NULL) dfs(root->left); if(root->right != NULL) dfs(root->right); // do something }迭代dfs, post_order traverse,稍微修改left,right顺序,就是previous_order traverse
void dfs(TreeNode *root) { if(root==NULL) return; stack<TreeNode *> x; unorder<TreeNode *,bool> m; x.push(root); while(!x.empty()){ t = x.top(); if(t->left != NULL && m[t->left] == 0) x.push(t->left); else if(t->right != NULL && m[t->right] == 0) x.push(t->right); else{ // do something m[t] = 1; x.pop(); } } }递归inorder
void inorder(TreeNode *root) { if(root==NULL) return; if(root->left != NULL) inorder(root->left); // do something with root if(root->right != NULL) inorder(root->right); }迭代inorder
void inorder(TreeNode *root) { if(root==NULL) return; stack<TreeNode *> x; unordered_map<TreeNode *,bool> m; TreeNode *t; x.push(back); while(!x.empty()){ t = x.top(); if(t->left != NULL && m[t->left] == 0){ t = t-left; x.push(t); } else{ x.pop(); m[t] = 1; // do something if(t->right != NULL) x.push(t->right); } } }
原文地址:http://blog.csdn.net/zcliatb/article/details/42583255