本文共 1873 字,大约阅读时间需要 6 分钟。
给定一个二叉树,返回其后续遍历的节点的值。例如:给定二叉树为 { 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 / 3return [3,2,1].Note: Recursive solution is trivial, could you do it iteratively?
直接上代码……
vector postorderTraversal(TreeNode* root) { if (root != NULL) { postorderTraversal(root->left); postorderTraversal(root->right); v.push_back(root->val); } return v;}
/*** 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 v; void postorderTraversalIter(TreeNode *root, stack&stac) { if (root == NULL) return; bool hasLeft = root->left != NULL; bool hasRight = root->right != NULL; stac.push(root); if (hasRight) stac.push(root->right); if (hasLeft) stac.push(root->left); if (!hasLeft && !hasRight) v.push_back(root->val); if (hasLeft) { root = stac.top(); stac.pop(); postorderTraversalIter(root, stac); } if (hasRight) { root = stac.top(); stac.pop(); postorderTraversalIter(root, stac); } if (hasLeft || hasRight) v.push_back(stac.top()->val); stac.pop(); } vector postorderTraversal(TreeNode* root) { stack stac; postorderTraversalIter(root, stac); return v; } };
另有两道类似的题目: