【LeetCode】145. Binary Tree Postorder Traversal

来源:互联网 发布:sql 删除表中所有数据 编辑:程序博客网 时间:2024/06/05 11:07

【LeetCode】145. Binary Tree Postorder Traversal


【题目描述】

  Given a binary tree, return the postorder traversal of its nodes' values.

  Note: Recursive solution is trivial, could you do it iteratively?


【输入输出】

  Given binary tree {1,#,2,3},

   1    \     2    /   3

  return [3,2,1].


【解题思路】

Morris traversal:时间复杂度:O(n)空间复杂度:O(1)


【代码】

class Solution {public:vector postorderTraversal(TreeNode* root) {if (!root) return vector();vector ans;while (true) {ans.insert(ans.begin(), root->val);if (!root->left && !root->right) break;TreeNode* p = root;if (p->right) {p = p->right;while (p->left) p = p->left;p->left = root->left;root->left = NULL;}root = (root->right) ? root->right : root->left;}return ans;}};

0 0