Java代码实现
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
if(root == null)
return;
TreeNode tmpNode = root.left;
root.left=root.right;
root.right=tmpNode;
Mirror(root.left);
Mirror(root.right);
}
}
Python代码实现
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if(root==None):
return root
tmp=root.left
root.left = root.right
root.right =tmp
self.Mirror(root.left)
self.Mirror(root.right)
(1)关于二叉树,由于其结构特性,基本所有题目都会或多或少和递归有关,前序、中序、后序、层次遍历一般会用到。
(2)自己在图上画下,第一步,交换根节点的两个子节点,第二步,思考下要变成题目上的样子,还需啥操作,是不是按先序检查子节点是否有子子节点,若有,交换,当然没有的话,空空交换也是可以的(虽然空空交换有点多余,但少写了代码判断,看着更简洁)。直到叶子节点的子节点(即空的时候,返回)。