Traversing through all nodes of a binary tree in Java

空扰寡人 提交于 2019-11-30 03:57:48

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

example:

consider this following Binary tree :

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);
    }
}

codeMan is right. The traversal will visit every node on the left. Once it reaches the last node on the left, it begins working its way back along the right-side nodes. This is a depth-first search (DFS) traversal. As such, each node is visited only once, and the algorithm runs in O(n) time. Happy coding.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!