156. Binary Tree Upside Down
Last updated
Last updated
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}/**
* Time complexity :
* Space complexity :
*/
class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
if(root == null) return null;
if(root.left == null && root.right == null) return root;
TreeNode newRoot = upsideDownBinaryTree(root.left);
root.left.left = root.right;
root.left.right = root;
root.left = null;
root.right = null;
return newRoot;
}
}/**
* Time complexity :
* Space complexity :
*/
class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
TreeNode curr = root;
TreeNode next = null;
TreeNode prev = null;
TreeNode temp = null;
while(curr != null) {
next = curr.left;
curr.left = temp;
temp = curr.right;
curr.right = prev;
prev = curr;
curr = next;
}
return prev;
}
}