
问题
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
说明:如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:Bonus points if you could solve it both recursively and iteratively.
示例
public class Program { public static void Main(string[] args) { var root = new TreeNode(1) { left = new TreeNode(2), right = new TreeNode(2) }; var res = IsSymmetric(root); Console.WriteLine(res); Console.ReadKey(); } public static bool IsSymmetric(TreeNode root) { return Symmetric(root, root); } public static bool Symmetric(TreeNode node1, TreeNode node2) { //都为空时,递归终止,为镜像二叉树 if(node1 == null && node2 == null) return true; //有一个为空时,递归终止,不是镜像二叉树 if(node1 == null || node2 == null) return false; //递归判定 return node1.val == node2.val && Symmetric(node1.left, node2.right) && Symmetric(node1.right, node2.left); } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } }
以上给出1种算法实现,以下是这个案例的输出结果:
True
分析:
显而易见,以上算法的时间复杂度为: 。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/4068。