zoukankan      html  css  js  c++  java
  • [LeetCode] Invert Binary Tree

    After reading the quote below the problem, you will be motivated to solve it immediately :-) Well, indeed it is also relative easy. The process of inverting a binary tree is simply 3 steps:

    1. Swap the left subtree and the right subtree;
    2. Invert the left subtree;
    3. Invert the right subtree.

    So we immediately have the following simple recursive solution.

     1 class Solution {
     2 public:
     3     TreeNode* invertTree(TreeNode* root) {
     4         if (!root) return NULL;
     5         swap(root -> left, root -> right);
     6         root -> left = invertTree(root -> left);
     7         root -> right = invertTree(root -> right);
     8         return root;
     9     }
    10 };

    Well, you may also want to challenge yourself to solve it iteratively. The iterative solution is basically a level-order traversal. Push all the nodes of the same level to a queue and then swap their left subtree and right subtree and iterate over their subtrees.

    The code is as follows.

     1 class Solution {
     2 public:
     3     TreeNode* invertTree(TreeNode* root) {
     4         if (!root) return NULL;
     5         queue<TreeNode*> level;
     6         level.push(root);
     7         while (!level.empty()) {
     8             TreeNode* node = level.front();
     9             level.pop();
    10             swap(node -> left, node -> right);
    11             if (node -> left) level.push(node -> left);
    12             if (node -> right) level.push(node -> right);
    13         }
    14         return root; 
    15     }
    16 };
  • 相关阅读:
    Web后台框架 目录
    C++ 目录
    【花书笔记】线性代数
    【Python数据挖掘概念、方法与实践】
    【统计学习基础】2. Overview of Supervised Learning
    字节与16进制
    【西瓜书】线性模型
    MySQL入门经典
    【机器学习基石】感知机模型
    python:web应用程序
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4572106.html
Copyright © 2011-2022 走看看