一.题目描述
翻转一颗二叉树
二. 解法
- 层序遍历法
/**
* 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 root;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
while(size != 0){
TreeNode front = queue.peek();
if(front.left == null){
front.left = front.right;
front.right = null;
}
else if(front.right == null){
front.right = front.left;
front.left = null;
}
else if(front.left != null && front.right != null){
TreeNode temp = front.left;
front.left = front.right;
front.right = temp;
}
queue.poll();
if(front.left != null)
queue.offer(front.left);
if(front.right != null)
queue.offer(front.right);
size--;
}
}
return root;
}
}
当进行层序遍历的时候,交换左和右孩子节点,要注意几种情形,左孩子为空,右孩子为空和左右孩子都不为空的情形,注意用else if不能用if。
- 递归
class Solution {
public TreeNode invertTree(TreeNode root) {
//递归函数的终止条件,节点为空时返回
if(root==null) {
return null;
}
//下面三句是将当前节点的左右子树交换
TreeNode tmp = root.right;
root.right = root.left;
root.left = tmp;
//递归交换当前节点的 左子树
invertTree(root.left);
//递归交换当前节点的 右子树
invertTree(root.right);
//函数返回时就表示当前这个节点,以及它的左右子树
//都已经交换完了
return root;
}
}
是一种自上而下的递归方法,先交换根节点的左右子树,再层层递归下去交换左右子树,从而达到翻转二叉树的效果。