题型一:非递归遍历二叉树后续
/**
* 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> postorderTraversal(TreeNode* root) {
map<TreeNode*,bool> mymap;
vector<int> ret;
stack<TreeNode*> mystac;
TreeNode* p=root;
while(p||!mystac.empty())
{
while(p)
{
mystac.push(p);
mymap[p]=false;
p=p->left;
}
if(!mystac.empty())
{
TreeNode* tmp=mystac.top();
mystac.pop();
if(mymap[tmp]==false)
{
mymap[tmp]=true;
mystac.push(tmp);
p=tmp->right;
}
else
{
ret.push_back(tmp->val);
p=NULL;
}
}
}
return ret;
}
};
题型二:非递归二叉序前序遍历(中序差不多,就不写了,自己去脑补去。。。。中序的逆序是直接先遍历右边再遍历左边,orz
vector<int> preorderTraversal(TreeNode *root) { // write your code here vector<int> ret; stack<TreeNode*> sta; TreeNode* p=root; while(sta.size()>0||p) { while(p) { sta.push(p); ret.push_back(p->val); p=p->left; } if(sta.size()) { TreeNode* tmp=sta.top(); sta.pop(); p=tmp->right; } } return ret; }
二叉树中和为某一值的路径:
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: void dfs(TreeNode* root,int e,int sum,vector<vector<int>>& ret,vector<int> tmp) { if(root) { if(sum+root->val==e&&root->left==NULL&&root->right==NULL) { tmp.push_back(root->val); ret.push_back(tmp); return; } tmp.push_back(root->val); dfs(root->left,e,root->val+sum,ret,tmp); dfs(root->right,e,root->val+sum,ret,tmp); } } vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { vector<vector<int>> ret; vector<int> tmp; dfs(root,expectNumber,0,ret,tmp); return ret; } };