Friday, August 2, 2019

LeetCode 156: Binary Tree Upside Down

https://leetcode.com/problems/binary-tree-upside-down/


Notes:
For tree-related questions, we usually can think about recursion. To this question, one way to think about it is that if we can finish f(root->left), then we just need to set root->left->right to the root, root->left->left to the root->right. and set root->left = NULL, and root->right = NULL. Done.

This is a bottom-up recursion.

See the code below:

  1. class Solution {
  2. public:
  3. TreeNode *upsideDownBinaryTree(TreeNode *root) {
  4. if (!root || !root->left) return root;//base case
  5. TreeNode *l = root->left, *r = root->right;
  6. TreeNode *res = upsideDownBinaryTree(l);
  7. l->left = r;
  8. l->right = root;
  9. root->left = NULL;
  10. root->right = NULL;
  11. return res;
  12. }
  13. };


A second way to solve this problem: iterative scan in a top-down fashion. Actually it is very similar to reverse a LinkedList.

See the code below:

  1. class Solution {
  2. public:
  3. TreeNode *upsideDownBinaryTree(TreeNode *root) {
  4. TreeNode *cur = root, *pre = NULL, *next = NULL, *tmp = NULL;
  5. while (cur) {
  6. next = cur->left;
  7. cur->left = tmp;
  8. tmp = cur->right;
  9. cur->right = pre;
  10. pre = cur;
  11. cur = next;
  12. }
  13. return pre;
  14. }
  15. };

No comments:

Post a Comment