Invert Binary Tree
Total Accepted: 54353 Total Submissions: 129489 Difficulty: Easy
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Invert Binary Tree
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
思路:
交换节点左右指针,再递归调用子节点。
<span style="font-weight: normal;">/**
* 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){
TreeNode* tem = root->left;
root->left = invertTree(root->right);
root->right = invertTree(tem);
}
return root;
}
};</span>