144. 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
My Answer
/**
* 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> preorderTraversal(TreeNode root) {
Stack<TreeNode> s = new Stack();
List<Integer> res = new ArrayList();
while(root!=null || !s.isEmpty()){
if(root==null){
root = s.pop();
}
res.add(root.val);
if(root.right!=null){
s.add(root.right);
}
root = root.left;
}
return res;
}
}
145. 二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
My Answer
/**
* 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) {
TreeNode p = root,r = null;
List<Integer> ans = new ArrayList();
Stack<TreeNode> s = new Stack();
while(!s.isEmpty() || p != null)
{
if(p != null)
{
s.add(p);
p = p.left;
}
else
{
p = s.peek();
if(p.right == null || p.right == r)
{
ans.add(p.val);
r = p;
s.pop();
p = null;
}
else
p = p.right;
}
}
return ans;
}
}