144. 二叉树的前序遍历
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
递归:
class Solution {
List<Integer>lsit = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null)
return lsit;
lsit.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return lsit;
}
}
栈
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null)
return new ArrayList<Integer>();
List<Integer>list = new ArrayList<Integer>();
Stack<TreeNode>stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.empty()){
TreeNode tnode = stack.pop();
list.add(tnode.val);
if(tnode.right != null){
stack.push(tnode.right);
}
if(tnode.left != null){
stack.push(tnode.left);
}
}
return list;
}
94. 二叉树的中序遍历
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
递归:
class Solution {
List<Integer>list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null)
return list;
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
}
栈
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer>list = new ArrayList<Integer>();
Stack<TreeNode>stack = new Stack<TreeNode>();
while(root != null || !stack.empty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
return list;
}
145. 二叉树的后序遍历
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
递归:
class Solution {
List<Integer>list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null)
return list;
postorderTraversal(root.left);
postorderTraversal(root.right);
list.add(root.val);
return list;
}
}
栈
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null)
return new ArrayList<Integer>();
List<Integer>list = new ArrayList<Integer>();
Stack<TreeNode>stack = new Stack<TreeNode>();
TreeNode prev = null;
while(root != null || !stack.empty()){
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.right == null || root.right == prev) {
list.add(root.val);
prev = root;
root = null;
} else {
stack.push(root);
root = root.right;
}
}
return list;
}
102. 二叉树的层序遍历
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
广搜(BFS)实现
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null)
return new ArrayList<>();
List<List<Integer>> llist= new ArrayList<>();
Queue<TreeNode>queue = new LinkedList<TreeNode>();
TreeNode newroot;
queue.offer(root);
while(!queue.isEmpty()){
List<Integer>list = new ArrayList<>();
int num =queue.size();
while(num > 0){
newroot = queue.poll();
list.add(newroot.val);
if(newroot.left != null)
queue.offer(newroot.left);
if(newroot.right != null)
queue.offer(newroot.right);
num--;
}
llist.add(list);
}
return llist;
}
}