1. 程式人生 > >演算法題(三十四):二叉樹的映象

演算法題(三十四):二叉樹的映象

題目描述

操作給定的二叉樹,將其變換為源二叉樹的映象。

輸入描述:

二叉樹的映象定義:源二叉樹 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	映象二叉樹
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

分析

判斷二叉樹是否是平衡二叉樹相似,可以用遞迴來做(後序遍歷)。

從下而上遞迴

從上而下

程式碼一

public class TreeMirrior {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode root = new TreeNode(1);
		root.left = new TreeNode(2);
		root.left.left = new TreeNode(3);
		root.right = new TreeNode(4);
		root.right.left = new TreeNode(5);
		root.right.right = new TreeNode(6);
		root.right.right.left = new TreeNode(7);
		mirror(root);
	}
	
	public static TreeNode mirror(TreeNode root){
		if(root == null){
			return null;
		}
		TreeNode left = mirror(root.left);
		TreeNode right = mirror(root.right);
		root.left = right;
		root.right = left;
		return root;
	}

}

程式碼二

public class Solution {
    public void Mirror(TreeNode root) {
        TreeNode tmp = null;
        if (root != null)
            {
            tmp = root.left;
            root.left = root.right;
            root.right = tmp;
            if (root.left != null)
                Mirror(root.left);
            if (root.right != null)
                Mirror(root.right);
        }
    }
}