How to Mirror a Binary Tree?
- 时间:2020-10-12 15:56:23
- 分类:网络文摘
- 阅读:198 次
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) —
推荐阅读:简便计算题:1997÷(1997+1997/1998)+(1/1999) 数学题:在比例尺1:5000的图纸上 2014年是平年还是闰年 数学题:在11次红灯变绿灯之间的黄灯亮起中 奥数题:从这两堆煤中分别运走同样的吨数后 数学题:用4cm长的线段表示实际距离1200km 数学题:一根圆柱形木头小明的爸爸将它锯成4段 奥数题:当王明在100m赛跑冲到终点时,领先刘铭10m 数学题:小敏要买一些圣诞卡 奥数题:一列火车匀速速度向北缓缓驶去
- 评论列表
-
- 添加评论