LeetCode 94. Binary Tree Inorder Traversal 树的前序、中序,后序遍历的非递归实现
2017-05-24 20:05
561 查看
题目
Binary Tree Inorder Traversal
Binary Tree Preorder Traversal
Binary Tree Postorder Traversal
思路
代码
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
以前序为例,先访问根节点:访问节点是由命令print来实现的,当有左右子树就压入栈中。
压入的顺序:右子树、左子树、根节点
Binary Tree Inorder Traversal
Binary Tree Preorder Traversal
Binary Tree Postorder Traversal
思路
代码
题目
94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes’ values.For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes’ values.For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
145. Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes’ values.For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
思路
三个题意都差不多,就是用非递归的方式实现树的三种遍历。这里选择使用栈的方式。以前序为例,先访问根节点:访问节点是由命令print来实现的,当有左右子树就压入栈中。
压入的顺序:右子树、左子树、根节点
代码
struct command{ string cmd; TreeNode *treenode; command(string str,TreeNode *tree):cmd(str),treenode(tree){} }; class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; if( root == NULL ) return res; stack<command> stack; stack.push(command("go",root)); while( !stack.empty() ){ command comd = stack.top(); stack.pop(); if(comd.cmd == "print") { res.push_back(comd.treenode->val); } else { //stack.push(command("print",comd.treenode)); 后序 if(comd.treenode->right != NULL) { stack.push(command("go",comd.treenode->right)); } //stack.push(command("print",comd.treenode)); 中序 if(comd.treenode->left != NULL) { stack.push(command("go",comd.treenode->left)); } //更改命令位置来实现前,中,后的三种遍历 stack.push(command("print",comd.treenode)); } } return res; } };
相关文章推荐
- leetcode笔试题二叉树的前序、中序、后序遍历的递归和循环c++实现
- 二叉树的先序、中序、后序遍历的递归和非递归实现
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- 二叉树先序、中序、后序遍历的非递归实现
- 二叉树的前序、中序、后序遍历 递归非递归实现
- 二叉树的遍历:前序、中序、后序、层序的非递归实现
- 前序、中序、后序遍历的多种非递归实现
- 二叉树先序、中序、后序遍历的非递归实现,纯c代码
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- 前序 中序 后序 遍历 递归 非递归算法 java实现
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- 二叉树先序,中序,后序遍历非递归实现
- java语言实现二叉树的前序、中序与后序遍历(递归与非递归)
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现(转)
- 二叉树先序、中序、后序遍历的非递归实现
- 二叉树的遍历;前序 中序 后序遍历二叉树;递归 非递归实现; 重建二叉树;编程之美重建二叉树
- 二叉树先序、中序、后序遍历的非递归实现
- 二叉树的创建,先序、中序、后序遍历的递归实现以及层序遍历
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- 用非递归实现二叉树的前序、中序、后序、层次遍历,用递归实现查找、统计个数、比较、求深度