Skip to content

Instantly share code, notes, and snippets.

@leosabbir
Created August 30, 2018 18:05
Class to invert a binary tree
/* File: InvertBinaryNode.java
* Created: 8/30/2018
* Author: Sabbir Manandhar
*
* Copyright (c) 2018 Hogwart Inc.
*/
//=======================================================================================
import java.util.Stack;
/**
* Class to invert a Binary Tree.
* Inversion of a binary tree means to invert all the left and right node. That is
* make left child right and right child left.
*
* @author Sabbir Manandhar
* manandharsabbir@gmail.com
* @version 1.0
*/
public class InvertBinaryTree {
/**
* This is a recursive method to invert the tree.
* @param root root of the tree to invert
* @return root of inverted tree
*/
public TreeNode invertTree(TreeNode root) {
if (root == null) return root;
invertTree(root.left);
invertTree(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
} // invertTree
//-------------------------------------------------------------------------------------
/**
* This is iterative method to invert the tree
* @param root root of the tree to invert
* @return root of inverted tree
*/
public TreeNode invertTreeIterative(TreeNode root) {
if (root == null) return root;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
return root;
}
} // InvertBinaryTree
//=======================================================================================
class TreeNode {
int val;
TreeNode left;
TreeNode right;
/**
* Constructor
* @param val
*/
public TreeNode(int val) {
this.val = val;
} // TreeNode
} // TreeNode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment