二叉樹的鏡像

題目描述

操作給定的二叉樹,將其變換爲源二叉樹的鏡像。 
輸入描述:
二叉樹的鏡像定義:源二叉樹 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	鏡像二叉樹
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

其實就是交換二叉樹的左右子樹,可用遞歸實現:

交換根節點的左右子樹,再分別對左子樹進行鏡像和右子樹進行鏡像

public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}


public class jingzi {
public void Mirror(TreeNode root) {
        if(root == null){
        return;
        }else{
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        Mirror(root.left);
        Mirror(root.right);
        }
    }
    public static void main(String[] args) {
 TreeNode root = new TreeNode(4);
 root.left = new TreeNode(5);
 root.right = new TreeNode(6);
 jingzi jj = new jingzi();
 jj.Mirror(root);
    }
}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章