Here I am trying to traverse my binary tree ( hard coded ) in post order. but after the first esle ( I have marked it by ***** is dead code. Would you please help? Here is my code. `package BnaryTree;
import java.util.Stack;
public class PostOrder {
private TreeNode root;
private class TreeNode {
private TreeNode left;
private TreeNode rigth;
private int data;
public TreeNode(int data) {
this.data = data;
}
}
public void createBinaryTree() {
TreeNode first = new TreeNode(1);
TreeNode second = new TreeNode(2);
TreeNode three = new TreeNode(3);
TreeNode four = new TreeNode(4);
TreeNode five = new TreeNode(5);
root = first;
first.left = second;
first.rigth= three;
second.left=four;
second.rigth= five;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PostOrder post= new PostOrder();
post.createBinaryTree();
post.postOrder();
}
public void postOrder() {
TreeNode current = root;
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() && current != null) {
if (current != null) {
stack.push(current);
current = current.left;
//*****
} else {
TreeNode temp = stack.pop().rigth;
if (temp == null) {
temp = stack.pop();
System.out.println(temp.data + " ");
while (!stack.isEmpty() & temp == stack.pop().rigth) {
temp = stack.pop();
System.out.println(temp.data + " ");
}
} else {
current = temp;
}
}
}
}
}`
Eclipse is messaging (Dead code ) but i am not sure why .Thank you.
You have dead code because the
whileloop condition ensures that when an iteration is made,currentis not null.By consequence, the
if (current != null)block will be executed as long as the loop makes iterations, and never theelseblock.The mistake is that the loop condition is a logical AND, while it should be a logical OR.
Some other remarks/problems:
The spelling of
rigthis wrong. Please change torighteverywhere in your codeWith
TreeNode temp = stack.pop().rigth;you lose track of the node that you popped from the stack, and it will never be in the output.The same loss happens with
temp == stack.pop().rigth... You can solve these two problems by calling.peek()instead.In the inner
whileloop you use the&bitwise operator: it does not perform short circuit evaluation. That means that even when the left side operand is false (i.e. the stack is empty), the right side operand will be evaluated, leading to a stack-related exception. You should use the logical operator&&.If you fix the above problems, the code will work: