给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList();
if(root == null)
return list;
Stack<TreeNode> stack = new Stack();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
list.add(cur.val);
if(cur.right != null){
stack.push(cur.right);
}
if(cur.left != null){
stack.push(cur.left);
}
}
return list;
}
}
class Solution {
List<Integer> list = new ArrayList();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null)
return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
给定一个二叉树,返回它的中序 遍历。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList();
if(root == null)
return list;
Stack<TreeNode> stack = new Stack();
TreeNode p = root;
while(!stack.isEmpty() || p != null){
while(p != null){//注意这里
stack.push(p);
p = p.left;
}
p = stack.pop();
list.add(p.val);
p = p.right;//注意这里
}
return list;
}
}
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList();
if(root == null)
return list;
Stack<TreeNode> stack1 = new Stack();
Stack<TreeNode> stack2 = new Stack();
stack1.push(root);
while(!stack1.isEmpty()){
TreeNode cur = stack1.pop();
stack2.push(cur);
if(cur.left != null){
stack1.push(cur.left);
}
if(cur.right != null)
stack1.push(cur.right);
}
while(!stack2.isEmpty()){
TreeNode cur = stack2.pop();
list.add(cur.val);
}
return list;
}
}
或者使用: Collections.reverse(list);
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList();
if(root == null)
return list;
Stack<TreeNode> stack = new Stack();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
list.add(cur.val);
if(cur.left != null){
stack.push(cur.left);
}
if(cur.right != null)
stack.push(cur.right);
}
Collections.reverse(list);
return list;
}
}