二叉树的镜像(反转二叉树)

反转二叉树----java实现

描述

实现二叉树的反转

示例:

原二叉树:

     4
   /   
  2     7
 /    / 
1   3 6   9
反转后的二叉树:
     4
   /   
  7     2
 /    / 
9   6 3   1

解析

递归

1.判断根是否为空,根为空直接返回根;否则继续;
2.递归反转根的左右子树

非递归

1.判断根是否为空,根为空直接返回根;否则继续;
2.交换根节点的左右子节点;
3. 交换第二层结点的左右子树;
4 重复下去,最后一个结点。

代码

递归

public TreeNode invertNode(TreeNode root) {  
                if(root==null)  
                    return root;  
        TreeNode temp=root.left;  
        root.left=invertNode(root.right);  
        root.right=invertNode(temp);  
        return root;  
    }  
//me
public
class Solution { public void Mirror(TreeNode root) { if (null == root) { return; } TreeNode temp = root.left; root.left = root.right; root.right = temp; Mirror(root.left); Mirror(root.right); } }

非递归

public TreeNode invertNode(TreeNode root) {  
        if(root == null)  
            return null;          
        Queue<TreeNode> queue = new LinkedList<TreeNode>();  
        queue.add(root);  
        while(!queue.isEmpty()){  
            TreeNode current = queue.poll();  
            TreeNode temp = current.left;  
            current.left = current.right;  
            current.right = temp;  
            if(current.left != null)  
                queue.add(current.left);  
            if(current.right != null)  
                queue.add(current.right);  
        }  
        return root;          
    }  
原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10727148.html