226. Invert Binary Tree

Total Accepted: 67715
Total Submissions: 155630
Difficulty: Easy

Invert a binary tree.

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

to

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

一种是用递归,一种是用栈,代码如下

C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        /*递归
        if (root == NULL) {
            return NULL;
        }

        TreeNode* left = root->left;
        TreeNode* right = root->right;
        root->left = invertTree(right);
        root->right = invertTree(left);
        return root;
        /*
        if(root==NULL)
            return root;
        queue<TreeNode *>q;
        q.push(root);
        while(!q.empty()){
            auto node=q.front();
            q.pop();
            auto temp=node->left;
            node->left=node->right;
            node->right=temp;
            if(node->left!=NULL)
                q.push(node->left);
            if(node->right!=NULL)
                q.push(node->right);
        }
        return root;
    }
};

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。