LeetCode:Binary Tree Traversal(二叉树遍历非递归)
2016-07-26 15:56
465 查看
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; } };
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- 文件遍历排序函数
- Lua 学习笔记之C API 遍历 Table实现代码
- C#遍历文件夹后上传文件夹中所有文件错误案例分析
- C#中遍历Hashtable的4种方法
- Erlang中遍历取出某个位置的最大值代码
- C++实现图的邻接矩阵存储和广度、深度优先遍历实例分析
- C++实现图的邻接表存储和广度优先遍历实例分析
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- 一波二叉树遍历问题的C++解答实例分享
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- php遍历目录方法小结
- 一个目录遍历函数
- php遍历删除整个目录及文件的方法
- PHP遍历文件夹与文件类及处理类用法实例
- PHP遍历XML文档所有节点的方法
- 平衡二叉树
- 二叉树