#
一天一道LeetCode本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 ##(一)题目
Invert a binary tree. 4 /
2 7 / \ /
1 3 6 9
to 4 /
7 2 / \ /
9 6 3 1
##(二)解题
题目大意:将一个二叉树倒置。即每个节点的左右节点交换位置。
解题思路:采用前序遍历,从根节点开始,对每个节点进行左右节点交换位置。
/**
* 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) {
dfsInvertTree(root);
return root;
}
void dfsInvertTree(TreeNode* root){
if(root==NULL) return;
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
if(root->left != NULL) dfsInvertTree(root->left);
if(root->right != NULL) dfsInvertTree(root->right);
}
};