树的相关算法
1.定义节点
public class Node<T> {
public T val;
public Node<T> left;
public Node<T> right;
public Node() {
}
public Node(T val) {
this.val = val;
}
public Node(T val, Node<T> left, Node<T> right) {
this.val = val;
this.left = left;
this.right = right;
}
}
2.树的遍历
1.前序遍历(深度优先遍历)
public static void preorder(Node root){
if(root != null){
System.out.print(root.val);
preorder(root.left);
preorder(root.right);
}
}
public static void preorder2(Node root){
LinkedList<Node> stack = new LinkedList<Node>();
Node p = root;
while (p != null || !stack.isEmpty()){
while(p != null){
System.out.print(p.val);
stack.push(p);
p = p.left;
}
Node node = stack.pop();
p = node.right;
}
}
2.中序遍历
public static void inorder(Node root){
if(root != null){
inorder(root.left);
System.out.print(root.val);
inorder(root.right);
}
}
public static void inorder2(Node root){
LinkedList<Node> stack = new LinkedList<Node>();
Node p = root;
while (p != null || !stack.isEmpty()){
while(p != null){
stack.push(p);
p = p.left;
}
Node node = stack.pop();
System.out.print(node.val);
p = node.right;
}
}
3.后序遍历
public static void postorder(Node root){
if(root != null){
postorder(root.left);
postorder(root.right);
System.out.print(root.val);
}
}
public static void postorder2(Node root){
LinkedList<Node> stack = new LinkedList<Node>();
LinkedList<Node> stack2 = new LinkedList<Node>();
Node p = root;
while (p != null || !stack.isEmpty()){
while(p != null){
stack.push(p);
stack2.push(p);
p = p.right;
}
Node node = stack.pop();
p = node.left;
}
while(!stack2.isEmpty()){
p = stack2.pop();
System.out.print(p.val);
}
}
4.层序遍历
public static void BFS(Node root){
LinkedList<Node> queue = new LinkedList<Node>();
queue.offer(root);
while(!queue.isEmpty()){
Node node = queue.poll();
System.out.print(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
案例测试
案例准备
Node node1 = new Node(1)
Node node2 = new Node(2)
Node node3 = new Node(3)
Node node4 = new Node(4)
Node node5 = new Node(5)
Node node6 = new Node(6)
node1.left = node2
node2.left = node4
node3.left = node6
方法使用结果
