LeetCode OJ 101Symmetric Tree

Posted xujian_2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 101Symmetric Tree相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/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

解题思路:题目大意为给定一个二叉树,判断是否为对称的镜像二叉树。解题思路有递归和非递归两种。

非递归的思路是层次遍历二叉树,每层的元素都是对称的。代码如下:

class TreeNode
{
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x)
	{
		val = x;
	}
}
public class Solution
{
	public boolean isSymmetric(TreeNode root)
	{
		if(root==null)
			return true;
		LinkedList<TreeNode> list=new LinkedList<>();  //层次遍历使用的队列
		LinkedList<TreeNode> list2=new LinkedList<>(); //每一次遍历后要将子节点放入队列中
		TreeNode node=null;
		list.addLast(root);
		while(!list.isEmpty())
		{
			LinkedList<Object> templist=new LinkedList<>();
			while(!list.isEmpty())
			{
				node=list.removeFirst();
				if(node.left==null)
				{
					templist.add("#");
				}
				else
				{
					templist.add(node.left.val);
					list2.add(node.left);
				}
				if(node.right==null)
				{
					templist.add("#");
				}
				else
				{
					templist.add(node.right.val);
					list2.add(node.right);
				}
			}
			if(!isSymmetric(templist))
			{
				//该层不对称,返回false
				return false;
			}
			else
			{
				//将子节点放入队列,继续遍历
				while(!list2.isEmpty())
				{
					list.addLast(list2.removeFirst());
				}
			}
		}
		return true;
	}
	//判断每一层遍历的结果是否为对称的
	private boolean isSymmetric(LinkedList<Object> templist) 
	{
		for(int i=0,j=templist.size()-1;i<=j;)
		{
			if(templist.get(i).equals(templist.get(j)))
			{
				i++;
				j--;
			}
			else
				return false;
		}
		return true;
	}
}

递归的代码如下:

public class Solution 
{
    public boolean isSymmetric(TreeNode root)
	{
		 if(root== null) return true;

        return ifSymmetric(root.left, root.right);        
    }
    public boolean ifSymmetric(TreeNode tree1, TreeNode tree2)
    {
        if(tree1==null && tree2==null)
            return true;
        else if(tree1 == null || tree2 == null)
            return false;
        if(tree1.val != tree2.val)
            return false;
        else
            return (ifSymmetric(tree1.left, tree2.right) && ifSymmetric(tree1.right, tree2.left));
    }
}


以上是关于LeetCode OJ 101Symmetric Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 101Symmetric Tree

&lt;LeetCode OJ&gt; 101. Symmetric Tree

LeetCode(101):Symmetric Tree

[LeetCode]题解(python):101 Symmetric tree

[LeetCode]题解(python):101-Symmetric Tree

Leetcode 101. Symmetric Tree