二叉树前序、中序、后序遍历主要就是递归实现。
层次遍历用队列进行实现。
前序遍历
/**
* 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> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList();
if(root == null){
return result;
}
result.add(root.val);
result.addAll(preorderTraversal(root.left));
result.addAll(preorderTraversal(root.right));
return result;
}
}
中序遍历
/**
* 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> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList();
if(root == null){
return result;
}
result.addAll(inorderTraversal(root.left));
result.add(root.val);
result.addAll(inorderTraversal(root.right));
return result;
}
}
后序遍历
/**
* 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> result = new ArrayList();
if(root == null){
return result;
}
result.addAll(postorderTraversal(root.left));
result.addAll(postorderTraversal(root.right));
result.add(root.val);
return result;
}
}
层次遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> results = new ArrayList();
Queue<TreeNode> treeQueue = new LinkedList();
Queue<Integer> indexQueue = new LinkedList();
if(root == null){
return results;
}
treeQueue.offer(root);
indexQueue.offer(0);
while(!treeQueue.isEmpty()){
TreeNode t = treeQueue.poll();
int index = indexQueue.poll();
List<Integer> item = null;
if(results.size() <= index){
item = new ArrayList();
item.add(t.val);
results.add(item);
}else{
item = results.get(index);
item.add(t.val);
}
if(t.left!=null){
treeQueue.offer(t.left);
indexQueue.offer(index + 1);
}
if(t.right!=null){
treeQueue.offer(t.right);
indexQueue.offer(index + 1);
}
}
return results;
}
}