Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Definition for a binary tree node.
- class TreeNode {
- int val;
- TreeNode left;
- TreeNode right;
- TreeNode(int x) {
- val = x;
- }
- }
- /**
- * Recursive Solution
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(N)
- *
- * N = Number nodes in the tree or the height of the tree.
- */
- class Solution1 {
- public TreeNode upsideDownBinaryTree(TreeNode root) {
- if (root == null || root.left == 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;
- }
- }
- /**
- * Iterative Solution
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(1)
- *
- * N = Number nodes in the tree or the height of the tree.
- */
- class Solution2 {
- public TreeNode upsideDownBinaryTree(TreeNode root) {
- if (root == null || root.left == null) {
- return root;
- }
- TreeNode cur = root;
- TreeNode pre = null;
- TreeNode preRight = null;
- while (cur != null) {
- TreeNode next = cur.left;
- cur.left = preRight;
- preRight = cur.right;
- cur.right = pre;
- pre = cur;
- cur = next;
- }
- return pre;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement