给你一棵二叉树的根节点?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
1、递归(相当于深度优先遍历)
2、迭代(相当于广度优先遍历)
法一:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
// Recursion
// Time: O(n), n 为节点数
// Space: O(m), m 为树深度
if (root == null) return root;
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
法二:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
// Iterator
// Time: O(n), n 为节点数
// Space: O(n)
if (root == null) return root;
// 将二叉树的节点逐层防区队列,然后迭代处理队列中的元素
Deque<TreeNode> deque = new ArrayDeque<>();
deque.addLast(root);
while (!deque.isEmpty()) {
// 每次从 队列 中取一个节点,对调它的左右子树
TreeNode tmp = deque.removeFirst();
TreeNode left = tmp.left;
tmp.left = tmp.right;
tmp.right = left;
// 若左子树不为空,则放入队列中进行后续处理
if (tmp.left != null) {
deque.addLast(tmp.left);
}
// 若右子树不为空,则放入队列中进行后续处理
if (tmp.right != null) {
deque.addLast(tmp.right);
}
}
// 返回处理后的结果
return root;
}
}
?