Invert a binary tree
Binary tree upside down
June 15, 2015
Write C# code
* Latest update: on June 16, 2015
* Leetcode:
* Invert a binary tree
* Reference:
* http://www.zhihu.com/question/31202353
*
* 7 lines of code - using recursion
*/
public static Node invertBinaryTree(Node root)
{
if (root == null)
return null;
Node temp = root.left;
root.left = root.right;
root.right = temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
return root;
}
/**
* Latest update: on June 16, 2015
* Leetcode: Invert a binary tree
* using iterative solution
*/
public static Node invertBinaryTreeIterative(Node root)
{
if (root == null)
return null;
Queue q = new Queue();
q.Enqueue(root);
/*
* consider the queue:
*/
while (q.Count > 0)
{
Node nd = (Node)q.Dequeue();
Node tmp = nd.left;
nd.left = nd.right;
nd.right = tmp;
if (nd.left != null)
q.Enqueue(nd.left);
if (nd.right != null)
q.Enqueue(nd.right);
}
return root;
}
No comments:
Post a Comment