二叉树前序中序后序遍历

mac2022-06-30  21

public class Node { int value; Node left=null; Node right=null; Node(int value){ this.value=value; } } public static Node BTrees(){ Node a=new Node(1); Node b=new Node(2); Node c=new Node(3); Node d=new Node(4); Node e=new Node(5); Node f=new Node(6); Node g=new Node(7); a.left=b;a.right=c; b.left=d;b.right=e; c.left=f;c.right=g; d.left=d.right=e.right=e.left=f.right=f.left=g.right=d.left=null; return a; } //前序遍历 public static void preOrderTraversal(Node root){ if(root==null){ return; } //跟+左子树+右子树; System.out.println(root.value); preOrderTraversal(root.left); preOrderTraversal(root.right); } //中序遍历 public static void inOrderTraversal(Node root){ if(root==null){ return; } //左子树+跟+右子树; inOrderTraversal(root.left); System.out.println(root.value); inOrderTraversal(root.right); } //后序遍历 public static void postOrderTraversal(Node root){ if(root==null){ return; } //左子树+右子树+跟 postOrderTraversal(root.left); postOrderTraversal(root.right); System.out.println(root.value); }

 

最新回复(0)