226.翻转二叉树
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
题解1:递归
/*
* @lc app=leetcode.cn id=226 lang=java
*
* [226] 翻转二叉树
*/
// @lc code=start
/**
* 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) {
// 递归法
// 时间复杂度:O(n)
// 空间复杂度:O(n)
if (root == null) {
return null;
}
// 翻转左右子树
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
// 递归处理左右子树
invertTree(root.left);
invertTree(root.right);
return root;
}
}
题解2:广度优先遍历
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import javax.swing.tree.TreeNode;
/*
* @lc app=leetcode.cn id=226 lang=java
*
* [226] 翻转二叉树
*/
// @lc code=start
/**
* 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) {
// 广度优先遍历
// 时间复杂度:O(n)
// 空间复杂度:O(n)
if (root == null) {
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
// 翻转左右子树
TreeNode temp = cur.left;
cur.left = cur.right;
cur.right = temp;
if (cur.left != null) {
// 左子树不为null,加入队列
queue.offer(cur.left);
}
if (cur.right != null) {
// 右子树不为null,加入队列
queue.offer(cur.right);
}
}
return root;
}
}
题解3:深度优先遍历
import java.util.LinkedList;
import java.util.Stack;
import javax.swing.tree.TreeNode;
/*
* @lc app=leetcode.cn id=226 lang=java
*
* [226] 翻转二叉树
*/
// @lc code=start
/**
* 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) {
// 深度优先遍历
// 时间复杂度:O(n)
// 空间复杂度:O(n)
if (root == null) {
return null;
}
Deque<TreeNode> stack = new LinkedList<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
for (int i = 0; i < stack.size(); i++) {
TreeNode cur = stack.pop();
// 翻转左右子树
TreeNode temp = cur.left;
cur.left = cur.right;
cur.right = temp;
if (cur.right != null) {
// 左子树不为null,加入栈
stack.push(cur.right);
}
if (cur.left != null) {
// 右子树不为null,加入栈
stack.push(cur.left);
}
}
}
return root;
}
}