How to Mirror a Binary Tree?

  • 时间:2020-10-12 15:56:23
  • 分类:网络文摘
  • 阅读:223 次

Given a binary tree like this:

 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11

Your task is to mirror it which becomes this:

    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

The most elegant algorithm to mirror a binary tree is using recursion. We can recursively mirror left and right trees respectively and then swap the left and right trees.

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
    public void Mirror(TreeNode root) {
        if (root == null) return;
        // make left tree also a mirror recursively
        Mirror(root.left);
        // make right tree also a mirror tree.
        Mirror(root.right);
        // swap left and right trees
        TreeNode t = root.left;
        root.left = root.right;
        root.right = t;        
    }
}
public class Solution {
    public void Mirror(TreeNode root) {
        if (root == null) return;
        // make left tree also a mirror recursively
        Mirror(root.left);
        // make right tree also a mirror tree.
        Mirror(root.right);
        // swap left and right trees
        TreeNode t = root.left;
        root.left = root.right;
        root.right = t;        
    }
}

The time complexity is O(N) where each node will be visited constant time, and the space complexity through calling stacks via recursion is O(N)=O(h) which is the height of the tree.

It is said that this is one of the Google’s interview question, a simple one though.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
亡羊补牢为时已晚  数学题:用哪种方法得到的税后利息多一些  数学题:从甲袋中拿走17块巧克力,并在乙袋中放入7块巧克力  数学题:结果在距离A地占全程的五分之四处和乙车相遇  数学题:经几秒钟两人第二次相遇  数学题:妈妈买苹果和梨各用去多少钱?  求年利率的数学题  丝瓜菌菇鸡蛋汤营养美味之夏季消暑佳品  数学题:王老师平均每月要付给银行多少利息  数学题:一列火车通过250米长的道路用25秒 
评论列表
添加评论