前提
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
递归遍历实现
(1)前序遍历
public static void preorder(TreeNode root)
{
if(root==null)return;
System.out.println(root.val);
preorder(root.left);
preorder(root.right);
}
中序遍历
public static void midorder(TreeNode root)
{
if(root==null)return;
midorder(root.left);
System.out.println(root.val);
midorder(root.right);
}
后序遍历
public static void postorder(TreeNode root)
{
if(root==null)return ;
postorder(root.left);
postorder(root.right);
System.out.println(root.val);
}
层序遍历
public static void levelorder(TreeNode root,int i,ArrayList list)
{
if(root==null)return ;
// list.size()
for(int j = 0;j<=i-length;j++)
{
list.add(length+j,null);
}
}
list.set(i,root.val);
levelorder(root.left,i*2,list);
levelorder(root.right,i*2+1,list);
}
迭代实现遍历
前序遍历
// 迭代实现前序遍历
public static void preorder(TreeNode root)
{
if(root!=null)
{
Stack stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty())
{
root = stack.pop();
if(root!=null)
{
System.out.println(root.val);
// 栈的特点是后入先出
stack.push(root.right);
stack.push(root.left);
}
}
}
}
中序遍历
// 迭代实现中序遍历
public static void midorder(TreeNode root)
{
if(root!=null)
{
Stack stack = new Stack<>();
while(!stack.isEmpty()||root!=null)
{
if(root!=null)
{
//直到找到最左节点为止
stack.push(root);
root = root.left;
}
else
{
//将内容进行取出
root = stack.pop();
//打印相应的值
System.out.println(root.val);
//开始找到的最左节点的右节点开始操作
root = root.right;
}
}
}
}
后序遍历
// 后序遍历实现递归操作
public static void postorder(TreeNode root)
{
if(root!=null)
{
Stack stack = new Stack<>();
TreeNode pre = null;
while(!stack.isEmpty()||root!=null)
{
//一直找到最左节点
while(root!=null)
{
stack.push(root);
root = root.left;
}
//将找到的节点进行弹出
root = stack.pop();
if(root.right==null||root.right==pre)
{
//只有该节点的右节点为空 或者已经打印过了
//才可以将此节点的内容进行打印输出
System.out.println(root.val);
//那么此时的前一个节点就是当前节点了
pre = root;
//为什么将此时的root设置成null
//为了避免该节点进入while的循环
root = null;
}
else
{
//如果该节点不符合右节点为null 或者 右节点已经被打印这个条件
//那么还得将这个节点重新压入栈中
stack.push(root);
//对该节点的右半部分进行相应操作
root = root.right;
}
}
}
}
层序遍历
// 迭代实现层序遍历
public static void levelOrder(TreeNode root)
{
Queue queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty())
{
TreeNode node = queue.poll();
if(node!=null)
{
System.out.println(node.val);
queue.add(node.left);
queue.add(node.right);
}
}
}