标签:中序 import util stat lis out value null travel
一、概念
1、前序遍历:
2、中序遍历:
3、后序遍历
4、层次遍历
从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印
二、代码
2.1 首先定义TreeNode
public class TreeNode {
public int value;
public TreeNode left;
public TreeNode right;
}
2.2 代码
import java.util.*;
public class Solution {
public static preOrderTravel(TreeNode root) {
if(root == null) {
return;
}
System.out.println(root.val);
if(root.left != null) {
preOrderTravel(root.left);
}
if(root.right != null) {
preOrderTravel(root.right);
}
}
public static void inOrderTravel(TreeNode root) {
if(root == null) {
return;
}
if(root.left != null) {
inOrderTravel(root.left);
}
System.out.println(root.val);
if(root.right != null) {
inOrderTravel(root.right);
}
}
public static void postOrderTravel(TreeNode root) {
if(root == null) {
return;
}
if(root.left != null) {
postOrderTravel(root.left);
}
if(root.right != null) {
postOrderTravel(root.right);
}
System.out.println(root.val);
}
public static void fromTopToBottom(TreeNode root) {
if(root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(queue.isEmpty()) {
// 移除并返问队列头部的元素 如果队列为空,则返回null
TreeNode node = queue.poll();
System.out.println(node.val);
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
}
}
标签:中序 import util stat lis out value null travel
原文地址:https://www.cnblogs.com/wylwyl/p/10658222.html