树的前序遍历
在这种遍历方法中,首先访问根节点,然后访问左子树,最后访问右子树。
我们从A开始,按照前序遍历,首先访问A本身,然后移动到它的左子树B。B也进行前序遍历。这个过程一直持续到所有节点都被访问为止。这棵树的前序遍历输出将是:
A → B → D → E → C → F → G
算法
直到所有节点都被遍历:
Step 1: Visit root node. Step 2: Recursively traverse left subtree. Step 3: Recursively traverse right subtree.
示例
class Node{ int data; Node leftNode, rightNode; Node() { leftNode = null; rightNode = null; this.data = data; } Node(int data) { leftNode = null; rightNode = null; this.data = data; } int getData() { return this.data; } Node getleftNode() { return this.leftNode; } Node getRightNode() { return this.leftNode; } void setData(int data) { this.data = data; } void setleftNode(Node leftNode) { this.leftNode = leftNode; } void setRightNode(Node rightNode) { this.leftNode = rightNode; } } public class PreOrderBinaryTree { public static void main(String[] args) { Node node = new Node(50); node.leftNode = new Node(60); node.leftNode.leftNode = new Node(45); node.leftNode.rightNode = new Node(64); node.rightNode = new Node(60); node.rightNode.leftNode = new Node(45); node.rightNode.rightNode = new Node(64); System.out.println("pre-order arrangement of given elements: "); preOrder(node); } public static void preOrder(Node root) { if(root !=null) { System.out.println(root.data); preOrder(root.leftNode); preOrder(root.rightNode); } } }
输出
pre-order arrangement of given elements: 50 60 45 64 60 45 64
广告