您的位置:首页 > 其它

LeetCode 94. Binary Tree Inorder Traversal 树的前序、中序,后序遍历的非递归实现

2017-05-24 20:05 561 查看
题目
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐