Interview Question

Member of Technical Staff IV Interview

-Sunnyvale, CA

Juniper Networks

Given a binary tree, how would you write program for getting mirror image of tree in O(n) time? Is it possible ? Assume you have no constraints on space.

Tags:data structures, algorithm, c, linux, tcp/ip
AnswerAdd Tags

Interview Answers

4 Answers

1

//call mirror( root, img_root) //img_node is passed by reference mirror (node, img_node ): if (node == NULL) return img_node.left = node.right img_node.right = mode.left mirror (node.right, img_node.left) mirror (node.left, img_node.right)

Naren on

0

Node mirror(Node node) { if (node == null) return node; /* do the subtrees */ Node left = mirror(node.left); Node right = mirror(node.right); /* swap the left and right pointers */ node.left = right; node.right = left; return node; }

Simple solution - Java on

0

Node mirror(Node node) { if (node == null) return node; Node left = node.left; Node right = node.right; node.left = mirror(right); node.right = mirror(left); return node; }

Anonymous on

1

if t is nul return; Mirror(Right) Mirror(Left) changeNodes(t)

Anonymous on

Add Answers or Comments

To comment on this, Sign In or Sign Up.