Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 * Definition for binary tree

  public class TreeNode {

      int val;

      TreeNode left;

      TreeNode right;

      TreeNode(int x) { val = x; }

  }

解析:

给你一个二叉树,判断其是否是中心轴对称的。

最好能够给出递归法和迭代法两种解法。

分析:

既然是中心对称的,那么深度为2的时候,左子树等于右子树,

深度为3时,左子树的左子树,等于右子树的右子树,左子树的右子树等于右子树的左子树,以此类推。

递归法:

	    public boolean isSymmetric(TreeNode root) {
	    	if(root==null) return true;
	    	return isSymmetric(root.left,root.right);
	    	
	    }
	    public boolean isSymmetric(TreeNode left,TreeNode right){
	    	if(left==null&&right==null) return true;
	    	if(left==null||right==null) return false;
	    	return left.val==right.val&&isSymmetric(left.left,right.right)&&isSymmetric(left.right, right.left);
	    }


    


迭代法:

迭代版就是使用一个栈,把root的左右子树入栈,然后每次pop2个,对比这两个node是否相等

然后把左子树的左子树和右子树的右子树,左子树的右子树和右子树的左子树入栈, 重复循环即可。


其实递归本质上就是一个栈, dfs本质也是用栈。

bfs本质用队列。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值