链接
https://leetcode-cn.com/problems/invert-binary-tree/
耗时
解题:5 min
题解:11 min
题意
翻转一棵二叉树。
4
/ \
2 7
/ \ / \
1 3 6 9
->
4
/ \
7 2
/ \ / \
9 6 3 1
思路
交换 dfs 到的每一个节点的左右子树。
时间复杂度:
O
(
n
)
O(n)
O(n) 树的节点数
AC代码
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return NULL;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)