144. Binary Tree Preorder Traversal
/**
* 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> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> node;
node.push(root);
while(!node.empty())
{
TreeNode *p=node.top();
node.pop();
res.push_back(p->val);
//先进右,再进左
if(p->right) node.push(p->right);
if(p->left) node.push(p->left);
}
return res;
}
};
94. Binary Tree Inorder Traversal
可以直接用cur判断左子树还要不要遍历,注释掉的布尔变量就是起这个作用的,后来发现别人这样写的,我觉得可以少个变量,挺不错的。
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> node;
node.push(root);
TreeNode *cur=root;
// bool bflag{true};
while((!node.empty()))
{
//直接用cur判断左子树还要不要遍历
while(cur&&cur->left)//&&bflag)
{
cur=cur->left;
node.push(cur);
}
// bflag=false;
cur=node.top();
res.push_back(cur->val);
node.pop();
if(cur->right)
{
node.push(cur->right);
cur=cur->right;
// bflag=true;
}
else
cur=nullptr;
}
return res;
}
};
145. Binary Tree Postorder Traversal
千万不要被hard给吓住,其实还蛮简单的,虽然我被吓到了,搞得我最后还看了好些人代码才写出来。但是,说实话,网上代码千奇百怪,有的很复杂,需要明眼看世界。
注意点:pre是前一个访问的点,要在往右边跑的时候判断该右子节点是否为pre。
Reference:
http://blog.csdn.net/hackbuteer1/article/details/6583988
/**
* 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) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> node;
node.push(root);
//pre记录上次被访问的节点
TreeNode *cur=root,*pre=nullptr;
while(!node.empty())
{
while(cur&&cur->left)
{
cur=cur->left;
node.push(cur);
}
cur=node.top();
//当此次要被访问的节点不是上次被访问的
if(cur->right&&cur->right!=pre)
{
cur=cur->right;
node.push(cur);
}
else
{
res.push_back(cur->val);
pre=cur;
node.pop();
cur=nullptr;
//右边访问结束,cur清空不再回父节点的左子树
}
}
return res;
}
};