Display the Odd Levels Nodes of a Binary Tree in JavaIn a binary tree, display the nodes of the odd level in any order. Consider the root node present at level 1. For the following binary tree: The odd level nodes are: 20 25 3 5 7. As we have to display the nodes in any order. Therefore, 20 25 5 3 7 can be displayed, or 25 3 7 5 20 can also be displayed. In fact, there are 5! = 5 x 4 x 3 x 2 x 1 = 120 ways to display the odd level nodes of a binary tree. Recursive ApproachThe concept is to pass the initial level as odd and do the switching of the level flag in each recursive call. For each node, if the odd flag is true, then display it. FileName: OddLevelNodes.java Output: The odd level nodes of the binary tree are: 20 25 3 7 5 Time Complexity: In the above program, every recursive call leads to two more recursive calls. Thus, the time complexity for computing each Iccanobif number is exponential, which is (2^{n}), where n represents the parameter num of the method findIccanobifNum(). The above program is consuming a lot of time to find the Iccanobif numbers. Thus, we need to optimize it further to reduce the time complexity. The following approach does the same. Iterative ApproachThe above program displays the node in the preorder way. However, if one wants the display the nodes level by level, we can use the concept of the level order traversal. FileName: OddLevelNodes1.java Output: The odd level nodes of the binary tree are: 20 25 3 5 7 Complexity Analysis: The time complexity, as well as the space complexity of the above program, is O(n), where n is the total number of nodes present in the binary tree. If we assign the false value like the following: boolean isOddLvl = false; We will get the nodes present at the even level. In the first program, we have invoked the method displayOddNodes() like the following: displayOddNodes(tn, false);
Next TopicJava Variable Declaration
