# Leetcode – 树的遍历总结（java）

### 前序遍历

public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> returnList = new ArrayList<Integer>();

if(root == null)
return returnList;

Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);

while(!stack.empty()){

TreeNode n = stack.pop();

if(n.right != null){
stack.push(n.right);
}
if(n.left != null){
stack.push(n.left);
}

}
return returnList;
}
}

### 中序遍历

//定义一个二叉树
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}

public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
//注意要重置声明的数据元素，因为对于每一个测试用例都会使用同一个实例
ArrayList<Integer> lst = new ArrayList<Integer>();

if(root == null)
return lst;

Stack<TreeNode> stack = new Stack<TreeNode>();
//定义一个指针来跟踪节点
TreeNode p = root;

while(!stack.empty() || p != null){

if(p != null){
stack.push(p);
p = p.left;
}else{
TreeNode t = stack.pop();
p = t.right;
}
}

return lst;
}
}

public class Solution {
List<Integer> result = new ArrayList<Integer>();

public List<Integer> inorderTraversal(TreeNode root) {
if(root !=null){
helper(root);
}

return result;
}

public void helper(TreeNode p){
if(p.left!=null)
helper(p.left);

if(p.right!=null)
helper(p.right);
}
}

### 后续遍历

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root==null) {
return res;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode temp = stack.peek();
if(temp.left==null && temp.right==null) {
TreeNode pop = stack.pop();
}
else {
if(temp.right!=null) {
stack.push(temp.right);
temp.right = null;
}
if(temp.left!=null) {
stack.push(temp.left);
temp.left = null;
}
}
}
return res;
}
}

### 层次遍历

public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> nodeValues = new ArrayList<Integer>();
if(root == null)
return al;

while(!current.isEmpty()){
TreeNode node = current.remove();

if(node.left != null)
if(node.right != null)

if(current.isEmpty()){
current = next;
nodeValues = new ArrayList();
}

}
return al;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Leetcode – 树的遍历总结（java） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)