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本质用队列。




你可能感兴趣的:(算法)