Traversing through all nodes of a binary tree in Java

前端 未结 2 1529
北海茫月
北海茫月 2020-12-28 18:05

Let\'s say I have a simple binary tree node class, like so:

public class BinaryTreeNode {
    public String identifier = \"\";
    public BinaryTreeNode pare         


        
2条回答
  •  忘掉有多难
    2020-12-28 18:38

    There are 3 types of Binary tree traversal that you can achieve :

    example:

    consider this following Binary tree :

    enter image description here

    Pre-order traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)
    In-order traversal sequence: A, B, C, D, E, F, G, H ,I (left, root, right)
    Post-order traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)
    

    code example:

    left to right traversal of the Binary tree, nay In order Traversal of binary tree :

    public void traverse (Node root){ // Each child of a tree is a root of its subtree.
        if (root.left != null){
            traverse (root.left);
        }
        System.out.println(root.data);
        if (root.right != null){
            traverse (root.right);
        }
    }
    

提交回复
热议问题