首页 > 学院 > 开发设计 > 正文

145. Binary Tree Postorder Traversal

2019-11-08 02:19:30
字体:
来源:转载
供稿:网友

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?

思路:利用镜像原则,后序:左右根。镜像后:根右左,可以用前序的迭代方法求出,然后在reverse下

/** * 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> ans; stack<TreeNode*> st; if(root == NULL) return ans; while(root != NULL || !st.empty()){ if(root){ while(root){ ans.push_back(root->val); st.push(root); root = root->right; } } else { root = st.top()->left; st.pop(); } } reverse(ans.begin(), ans.end()); return ans; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表