226. Invert Binary Tree(C++)

226. Invert Binary Tree

Invert a binary tree.

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

to

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




代码实现
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* invertTree(TreeNode* root) {
13         if(!root) return root;
14         if(root->left!=nullptr||root->right!=nullptr)
15         {
16             swap(root->left,root->right);
17             root->left=invertTree(root->left);
18             root->right=invertTree(root->right);
19         }
20         return root;
21     }
22 };

 

posted @ 2016-05-14 17:13  19Q3  阅读(176)  评论(0编辑  收藏  举报