题目:
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]
.
解题思路:
使用递归的方法最容易写,代码如下所示:
递归代码:
/** * Definition for binary tree * 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; if (root == NULL) return ans; vector<int> left = postorderTraversal(root->left); vector<int> right = postorderTraversal(root->right); for (int i = 0; i < left.size(); i++) { ans.push_back(left[i]); } for (int i = 0; i < right.size(); i++) { ans.push_back(right[i]); } ans.push_back(root->val); return ans; } };
题目要求使用非递归的方法来遍历,后序遍历的非递归算法比前序要难一些,所以一种考虑就是将问题转化为前序遍历,最后再将结果翻转后返回。代码如下:
转化为前序遍历的代码:
/** * Definition for binary tree * 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; if (root == NULL) return ans; TreeNode *cur; stack<TreeNode *> st; st.push(root); while (!st.empty()) { cur = st.top(); st.pop(); ans.push_back(cur->val); if (cur->left != NULL) { st.push(cur->left); } if (cur->right != NULL) { st.push(cur->right); } } reverse(ans.begin(), ans.end()); return ans; } };
还有一种方法是直接采用非递归来进行后序遍历,需要设置一个pre指针来标示上次访问的节点。访问当前根节点的条件为没有右结点,或者右节点为上次输出的节点。
后序遍历的非递归算法如下:
/** * Definition for binary tree * 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; if (root == NULL) return ans; TreeNode *cur = root, *pre = NULL;//pre表示上次输出的节点 stack<TreeNode *> st; while (cur != NULL || !st.empty()) { if (cur != NULL) { //根指针进栈,遍历左子树 st.push(cur); cur = cur->left; } else { cur = st.top(); // 取得结点 if (cur->right == NULL || cur->right == pre) { //如果没有右结点,或者右节点为上次输出的节点,访问该节点 ans.push_back(cur->val); st.pop(); pre = cur; cur = NULL; } else { //当前时刻,不能访问该节点 cur = cur->right; } } } return ans; } };