Monday, October 26, 2020

Invert a binary tree

Problem: Given the root of a binary tree, invert the tree, and return its root.

Example:
 

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1


Approach: Using Post order traversal (Bottom up approach).


Implementation in C#:

        public void Invert()
        {
            if (this.Root == null)
            {
                return;
            }

            this.Root = this.Invert(this.Root);
        }

        private BinaryTreeNode Invert(BinaryTreeNode node)
        {
            if (node == null)
            {
                return null;
            }

            BinaryTreeNode left = this.Invert(node.LeftNode);
            BinaryTreeNode right = this.Invert(node.RightNode);

            node.LeftNode = right;
            node.RightNode = left;
            return node;
        }


Complexity: O(n)

No comments:

Post a Comment