二叉树的后序遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
/** * 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 > path;
postOrder(root, path);
return path;
}
/*
void postOrder(TreeNode* root, vector<int> &path)
{
//递归写法
if (root)
{
postOrder(root->left, path);
postOrder(root->right, path);
path.push_back(root->val);
}
}
*/
void postOrder(TreeNode* root, vector< int > &path)
{
//非递归写法
stack<TreeNode *> TreeNodeStack;
TreeNode *plastvisit = NULL; //记录结点是否访问过
while (root != NULL || !TreeNodeStack.empty())
{
while (root != NULL)
{
TreeNodeStack.push(root);
root = root->left;
}
root = TreeNodeStack.top();
if (root->right == NULL || plastvisit == root->right)
{
path.push_back(root->val);
plastvisit = root;
TreeNodeStack.pop();
root = NULL;
}
else
root = root->right;
}
}
};
|