描述
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
示例 2:输入:root = [2,1,3]
输出:[2,3,1]
示例 3:输入:root = []
输出:[]提示:
树中节点数目范围在 [0, 100] 内
-100 <= Node.val <= 100
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/invert-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
C++代码
1、递归实现
先来看递归的方法,写法非常简洁,五行代码搞定,交换当前左右节点,并直接调用递归即可
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return nullptr;
TreeNode* temp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(temp);
return root;
}
};
2、非递归实现
非递归的方法也不复杂,跟二叉树的层序遍历一样,需要用queue来辅助,先把根节点排入队列中,然后从队中取出来,交换其左右节点,如果存在则分别将左右节点在排入队列中,以此类推直到队列中木有节点了停止循环,返回root即可
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return nullptr;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int n = q.size();
for(int i=0; i<n; i++){
auto node = q.front();
q.pop();
swap(node->left, node->right);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
}
return root;
}
};
Python代码
1、递归实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
temp = root.left
root.left = self.invertTree(root.right)
root.right = self.invertTree(temp)
return root
2、非递归实现
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
q = [root]
while q:
n = len(q)
for i in range(n):
node = q.pop(0)
temp = node.left
node.left = node.right
node.right = temp
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return root