题目描述
求给定的二叉树的后序遍历。
例如:
给定的二叉树为{1,#,2,3},
1↵ ↵ 2↵ /↵ 3↵
返回[3,2,1].
备注;用递归来解这道题太没有新意了,可以给出迭代的解法么?
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?
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//先实现二叉树的递归遍历
/*
class Solution {
public:
vector<int> ans;
vector<int> postorderTraversal(TreeNode *root) {
if(root == NULL) return ans;
postorder(root);
return ans;
}
void postorder(TreeNode *root)
{
if(root != NULL)
{
postorder(root->left);
postorder(root->right);
ans.push_back(root->val);
}
}
};
*/
//二叉树的迭代遍历
/*
当你调用一个函数时,系统会将这个函数进行入栈操作,在入栈之前,通常需要完成三件事。
1、将所有的实参、返回地址等信息传递给被调函数保存。
2、为被调函数的局部变量分配存储区。
3、将控制转移到被调函数入口。
当一个函数完成之后会进行出栈操作,出栈之前同样要完成三件事。
1、保存被调函数的计算结果。
2、释放被调函数的数据区。
3、依照被调函数保存的返回地址将控制转移到调用函数。
上述操作必须通过栈来实现,即将整个程序的运行空间安排在一个栈中。每当运行一个函数时,就在栈顶分配空间,函数退出后,释放这块空间。
所以当前运行的函数一定在栈顶。
为了把一个递归过程改为非递归过程,就需要自己维护一个辅助栈结构,记录遍历时的回退路径。非递归的快速排序的设计依据也是这个。
*/
/*
public void preOrder(Node root) {
if(root == null) return;
Node cur = root;
Stack<Node> stack = new Stack<Node>();
stack.push(cur);
while(!stack.isEmpty()) {
cur = stack.pop();
System.out.print(cur.value);
if(cur.rChild != null) stack.push(cur.rChild);
if(cur.lChild != null) stack.push(cur.lChild);
}
}
*/
class Solution {
public:
vector<int> ans;
vector<int> postorderTraversal(TreeNode *root) {
if(root == NULL) return ans;
TreeNode *cur = root;
stack<TreeNode*> s;
s.push(cur);
while(!s.empty())
{
cur = s.top();
s.pop();
if(cur->left != NULL) s.push(cur->left);
if(cur->right != NULL) s.push(cur->right);
ans.push_back(cur->val);
}
reverse(ans.begin(), ans.end());
return ans;
}
};
//前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> ans;
if(root == NULL) return ans;
stack<TreeNode*> s;
s.push(root);
TreeNode* cur;
while(!s.empty())
{
cur = s.top();
s.pop();
ans.push_back(cur->val);
if(cur->right != NULL) s.push(cur->right);
if(cur->left != NULL) s.push(cur->left);
}
return ans;
}
};

本文深入探讨了二叉树的遍历算法,包括递归和迭代方法,详细解析了前序、中序和后序遍历的具体实现,以及如何通过栈结构优化迭代遍历过程。
747

被折叠的 条评论
为什么被折叠?



