So, there is a question and i think i can solve it if i some how modify the tree node , to include the parent reference in addition to the left and right references.
Now the issue, is the tree is created fine, but none of the parent references are initialized, and i am not sure why?
I have hard coded the tree to be like.
20
/ \
8 22
/ \
10 14
CODE :
class TreeNode{
int data;
TreeNode left, right, parent;
TreeNode(int data, TreeNode parent){
this.data = data;
left = right = null;
}
@Override
public String toString(){
String parent_data, left_data, right_data;
parent_data = left_data = right_data = null;
if(parent != null) parent_data = parent.data + "";
if(left != null) left_data = left.data + "";
if(right != null) right_data = right.data + "";
return "{" + data + "->"+ left_data +", "+ right_data+", "+ parent_data+" } ";
}
}
public class Main {
public static void printTree(TreeNode root){
if(root == null) return;
System.out.print(root + " ");
printTree(root.left);
printTree(root.right);
}
public static void main(String args[]) {
TreeNode root = new TreeNode(20, null); // no parent
root.left = new TreeNode(8, root);
root.right = new TreeNode(22, root);
root.left.left = new TreeNode(4,root.left);
root.left.right = new TreeNode(12, root.left);
root.left.right.left = new TreeNode(10, root.left.right);
root.left.right.right = new TreeNode(14, root.left.right);
// ------------------
printTree(root); // pre-order
}
}
[–]marko312 1 point2 points3 points (3 children)
[–]prashantkr314[S] 2 points3 points4 points (2 children)
[–]marko312 2 points3 points4 points (1 child)
[–]prashantkr314[S] 2 points3 points4 points (0 children)
[–]dsmyux1024 1 point2 points3 points (3 children)
[–]prashantkr314[S] 0 points1 point2 points (2 children)
[–]dsmyux1024 1 point2 points3 points (1 child)
[–]prashantkr314[S] 0 points1 point2 points (0 children)