// 二叉树节点定义
public class BinaryTreefanzhuan {
class TreeNode{
int value;
TreeNode left;
TreeNode right;
}
// 递归
public static TreeNode invertNode(TreeNode root){
if (root == null) return null;
TreeNode temp = root.left;
root.left = invertNode(root.right);
root.right = invertNode(temp);
return root;
}
// 非递归
//交换左右节点后,将这个两个节点放入队列,继续下一层交换
public static TreeNode invertNode2(TreeNode root){
if (root == null) return null;
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
while(!nodeQueue.isEmpty()){
TreeNode current = nodeQueue.poll();
TreeNode temp = current.left;
current.left = current.right;
current.right = temp;
if (current.left != null) nodeQueue.add(current.left);
if (current.right != null) nodeQueue.add(current.right);
}
return root;
}