LeetCode刷题实战145:二叉树的后序遍历
共 1692字,需浏览 4分钟
·
2021-01-09 16:38
Given the root of a binary tree, return the postorder traversal of its nodes' values.
题意
解题
/**
* 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> result;
setvisited;//用于标记已经访问过的节点
stackmyStack;//辅助栈,用于保留现场
while (root != NULL || !myStack.empty()) {
if (root != NULL) {
myStack.push(root);//栈先保护根节点的现场
visited.insert(root);//标记根节点已访问
if (root->right) {//右子树不为空,保护右子树现场
myStack.push(root->right);
}
root = root->left;//现场转移至左子树
continue;
}
root = myStack.top();//恢复现场
myStack.pop();
while (visited.find(root) != visited.end()) {//如果这个节点已经访问过(根节点)
result.push_back(root->val);
if (!myStack.empty()) {
root = myStack.top();//再恢复现场
myStack.pop();
}
else {
root == NULL;
return result;
}
}
}
return result;
}
};