LeetCode刷题实战226:翻转二叉树
共 2412字,需浏览 5分钟
·
2021-04-01 14:00
Given the root of a binary tree, invert the tree, and return its root.
示例
解题
class Solution {
public:
TreeNode* invertTree(TreeNode* root)
{
if(root ==NULL) return root;
TreeNode* node = invertTree(root->left);
root->left = invertTree(root->right);
root->right = node;
return root;
}
};
public class Solution {
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
if(root!=null) q.offer(root);
while(!q.isEmpty()){
TreeNode curr = q.poll();
TreeNode tmp = curr.right;
curr.right = curr.left;
curr.left = tmp;
if(curr.left!=null) q.offer(curr.left);
if(curr.right!=null) q.offer(curr.right);
}
return root;
}
}