对称二叉树

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [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

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

第一种使用递归意思也很简单,就是不断依次从外向内比较俩个节点是否相同:

        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public static bool Method1(TreeNode root)
        {
            if (root == null) return true;
            return CompareRoot(root.left, root.right);
        }

        private static bool CompareRoot(TreeNode lRoot, TreeNode RRoot)
        {
            if (lRoot == null) return RRoot == null;
            if (RRoot == null) return false;
            if (lRoot.val != RRoot.val) return false;
            return (lRoot.val == lRoot.val) && CompareRoot(lRoot.left, RRoot.right) && CompareRoot(lRoot.right, RRoot.left);
        }

迭代的话我是用循环的中序遍历,然后打印出的中序遍历结果再做判断,也就是对称的就是回文这点进行判断:

        /// <summary>
        /// 非递归实现
        /// </summary>
        /// <returns></returns>
        public static bool Method2(TreeNode root)
        {
            List<int> listNums = new List<int>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode pNode = root;
            //循环中序遍历
            while (pNode != null || stack.Count > 0)
            {
                if (pNode != null)
                {
                    stack.Push(pNode);
                    pNode = pNode.left;
                }
                else
                {
                    TreeNode node = stack.Pop();
                    listNums.Add(node.val);
                    pNode = node.right;
                }
            }
            //判断是否是回文,是就是对称二叉树
            for (int i = 0; i < listNums.Count >> 1; i++)
            {
                if (listNums[i] != listNums[listNums.Count - 1 - i]) return false;
            }
            return true;
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值