【LeetCode】145.Binary Tree Postorder Traversal(Hard)解题报告
题目地址:https://leetcode.com/problems/binary-tree-postorder-traversal/description/
题目描述:
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?题目要求不可以使用递归,实际是树的后序遍历。那么我们利用stack,并加一个标记,每个节点访问两次就可以以
Solution1:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<NodeContainer> stack = new Stack<>();
TreeNode current = root;
while(!stack.isEmpty() || current!=null){
while(current!=null){
NodeContainer nc = new NodeContainer(false,current);
stack.push(nc);
current = current.left;
}
NodeContainer nc = stack.pop();
TreeNode node = nc.node;
if(!nc.visited){
nc.visited=true;
stack.push(nc);
current = node.right;
}else{
list.add(node.val);
}
}
return list;
}
class NodeContainer{
boolean visited;
TreeNode node;
public NodeContainer(boolean visited,TreeNode node){
this.visited = visited;
this.node = node;
}
}
}
Solution2:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
两种方法:一种递归,一种stack
time : o(n)
space : O(n)
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
helper(res,root);
return res;
}
public static void helper(List<Integer> res,TreeNode root){
if(root == null) return;
helper(res,root.left);
helper(res,root.right);
res.add(root.val);
}
}
Solution3:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
两种方法:一种递归,一种stack
time : o(n)
space : O(n)
用stack求后序遍历
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
res.addFirst(cur.val);
if(cur.left != null) stack.push(cur.left);
if(cur.right != null) stack.push(cur.right);
}
return res;
}
}
Date:2017年12月12日