返回顶部

[226] Invert Binary Tree

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

翻转一棵二叉树。EZ题。
方法1:整体思路就是层次遍历,然后把左右孩子对调。
 1 class Solution {
 2 public:
 3     TreeNode* invertTree(TreeNode* root) 
 4     {
 5         queue<TreeNode*> q;
 6         if(root!=nullptr)
 7         {
 8             q.push(root);
 9             while(!q.empty())
10             {
11                TreeNode* node = q.front();
12                 q.pop();
13                swapChild(node);
14                if(node->left!=nullptr)
15                    q.push(node->left);
16                 if(node->right!=nullptr)
17                     q.push(node->right);
18             }
19         }
20         return root;
21     }
22     void swapChild(TreeNode* node)
23     {
24         if(node != nullptr)
25         {
26             TreeNode* temp = node->right;
27             node->right = node->left;
28             node->left = temp;
29         }
30     }
31 };

方法2:递归求解,简洁的让人觉得可怕,跑的还飞快,推荐食用👍

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) 
    {
        if(root!=nullptr)
        {
            
            auto temp = root->right;
            root->right = invertTree(root->left);
            root->left = invertTree(temp);
        }
        return root;
    }
};

 

posted @ 2019-07-10 00:31  Swetchine  阅读(167)  评论(0编辑  收藏  举报