博文中会简要介绍Leetcode P0145题目分析及解题思路。
“Binary Tree Postorder Traversal”也是一道比较基础的题目,这道题考察的是对二叉树后序遍历,有点像p0144的对偶问题。这道题也是需要分别用迭代和递归来实现解法。
迭代的方法有两种思路,一种是会破坏树的结构,能解出来这道题但是没什么实际的应用价值,虽然可以用HashTable等容器来记忆化访问,但是终归复杂化了简单问题。
另一种是借鉴p0144的思路,考虑前序遍历的对偶问题,这样一来无需改变树结构就可以得到最终的后序遍历结果。
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
Follow up: Recursive solution is trivial, could you do it iteratively?
下述解法会破坏树的结构,虽然能得到后序遍历的结果但是应用价值几乎为零。
以下是Java的题解代码实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> postorder = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
// Find the deepest left subtree
while (curr != null) {
stack.offerFirst(curr);
curr = curr.left;
}
curr = stack.peekFirst();
if (curr.right == null) {
curr = stack.pollFirst();
postorder.add(curr.val);
}
TreeNode child = curr.right;
curr.right = null;
curr = child;
}
return postorder;
}
}
上述代码的不足之处在于会改变当前树的结构,虽然可以使用HashTable之类的容器来解决这种缺陷,但终归不是足够鲁棒。
而下面的代码实际上就是前序遍历的翻转或者说镜面。前序遍历是向先向左子树遍历,而这里后序遍历先向右子树遍历,唯一不同的是,由于后序遍历总是先左子树后右子树最后再访问当前结点,所以我们在插入时需要每次都在头部插入,这样就能保证,先插入的根结点其实是在最末尾的。
以下是第二种Java的题解代码实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> postorder = new LinkedList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
postorder.offerFirst(curr.val);
stack.offerFirst(curr);
curr = curr.right;
}
curr = stack.pollFirst();
curr = curr.left;
}
return postorder;
}
}
以下是C++的题解代码实现。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
this->_Dfs(root);
return this->postorder_;
}
private:
vector<int> postorder_;
void _Dfs(TreeNode *curr) {
if (!curr)
return;
if (curr->left)
this->_Dfs(curr->left);
if (curr->right)
this->_Dfs(curr->right);
this->postorder_.push_back(curr->val);
}
};