0226. 翻转二叉树
最后更新于
这有帮助吗?
这有帮助吗?
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function (root) {
if (!root) return root;
// 递归
// const left = root.left;
// const right = root.right;
// root.right = invertTree(left);
// root.left = invertTree(right);
// 我们用stack来模拟递归
// 本质上递归是利用了执行栈,执行栈也是一种栈
// 其实这里使用队列也是一样的,因为这里顺序不重要
const stack = [root];
let current = null;
while ((current = stack.shift())) {
const left = current.left;
const right = current.right;
current.right = left;
current.left = right;
if (left) {
stack.push(left);
}
if (right) {
stack.push(right);
}
}
return root;
};# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
stack = [root]
while stack:
node = stack.pop(0)
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root/**
* 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) {
if (root == NULL) return root;
auto q = queue<TreeNode*>();
q.push(root);
while (!q.empty()) {
auto n = q.front(); q.pop();
swap(n->left, n->right);
if (n->left != nullptr) {
q.push(n->left);
}
if (n->right != nullptr) {
q.push(n->right);
}
}
return root;
}
};