两种方法,递归和迭代,递归思想是将当前节点的子节点交换后调用自身方法继续交换两个子节点的子节点,迭代思想是利用层序遍历的思想,代码也类似。
/**
* 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) {
if (root == null) {return null;}
//用队列存放节点
ArrayDeque<TreeNode> deque = new ArrayDeque<>();
deque.offer(root);
while (!deque.isEmpty()) {
int size = deque.size();
while (size-- > 0) {
TreeNode node = deque.poll();
//交换当前节点的子节点,然后继续向队列存放子节点循环遍历。
swap(node);
if (node.left != null) {deque.offer(node.left);}
if (node.right != null) {deque.offer(node.right);}
}
}
return root;
}
private void swap(TreeNode root) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
递归:本题可用前序和后序递归
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return root;
invertTree(root.left);
invertTree(root.right);
swap(root);
return root;
}
private void swap(TreeNode root) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}