前提
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 ;
int length =list.size();
if(length<=i)
{
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<TreeNode> 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<TreeNode> 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<TreeNode> 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;
}
else
{
stack.push(root);
root = root.right;
}
}
}
}
层序遍历
public static void levelOrder(TreeNode root)
{
Queue<TreeNode> 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);
}
}
}