二叉树的遍历
二叉树的表示
//Java
public class TreeNode{
int val;
Node left,right;
public Node(int val){
this.val=val;
}
}
前序遍历
递归方法
public static void preOrder1(TreeNode root){
if(root == null)
return;
System.out.println(root.val);
preOrder1(root.left);
preOrder1(root.right);
}
非递归方法
public static void preOrder2(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode node =root;
while(node!=null || !stack.empty()){
if(node!=null){
System.out.println(node.val);
stack.push(node);
node = node.left;
}else{
node = stack.pop();
node =node.right;
}
}
}
中序遍历
递归方法
public static void inOrder1(TreeNode root){
if(root == null)
return;
inOrder1(root.left);
System.out.println(root.val);
inOrder1(root.right);
}
非递归方法
//非递归方法
public static void inOrder2(TreeNode root){
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node= root;
while(node!=null || !stack.empty()){
if(node != null){
stack.push(node);
node = node.left;
}else {
node = stack.pop();
System.out.println(node.val);
node = node.right;
}
}
}
后序遍历
递归方法
public static void postOrder1(TreeNode root){
if(root == null)
return;
postOrder1(root.left);
postOrder1(root.right);
System.out.println(root.val);
}
非递归方法
//非递归方法
public static void postOrder2(TreeNode root){
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node =root;
TreeNode lastNode =root;
while(node != null || !stack.empty()){
while(node != null){
stack.push(node);
node = node.left;
}
node = stack.peek();
if(node.right == null || node.right == lastNode){
System.out.println(node.val);
stack.pop();
lastNode = node;
node =null;
}else {
node = node.right;
}
}
层序遍历
public static void LevelorderTraversal ( TreeNode root )
{
LinkedList<TreeNode> Q = new LinkedList<TreeNode>();
TreeNode node =root;
if ( node == null ) return; /* 若是空树则直接返回 */
Q.offer(node);
while ( !Q.isEmpty() ) {
node = Q.poll();
System.out.println( node.val); /* 访问取出队列的结点 */
if ( node.left != null ) Q.offer(node.left);
if ( node.right != null ) Q.offer(node.right);
}
}