文章目录
- 题目描述
- 思路
- 复杂度
- Code
题目描述
思路
利用二叉树的先序遍历,每次递归遍历时将当前节点的左右子节点交换即可
复杂度
时间复杂度:
O ( n ) O(n) O(n);其中 n n n为树节点的个数
空间复杂度:
O ( h e i g h ) O(heigh) O(heigh);其中 h e i g h t height height为树的高度
Code
class Solution {
public:
/**
*
* @param root The root of binary tree
* @return TreeNode*
*/
TreeNode *invertTree(TreeNode *root) {
traverse(root);
return root;
}
/**
* Binary tree traversal function
*
* @param root The root of binary tree
*/
void traverse(TreeNode *root) {
if (root == nullptr) {
return;
}
//All each node needs to do is swap its left and right child nodes
TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
//Traverse the nodes of the left and right subtree
traverse(root->left);
traverse(root->right);
}
};