【LeetCode OJ 101】Symmetric 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));
    }
}
时间: 2024-11-04 22:35:19

【LeetCode OJ 101】Symmetric Tree的相关文章

【LeetCode OJ 075】Sort Colors

题目链接:https://leetcode.com/problems/sort-colors/ 题目:Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0,

【LeetCode OJ 14】Longest Common Prefix

题目链接:https://leetcode.com/problems/longest-common-prefix/ 题目:Write a function to find the longest common prefix string amongst an array of strings. 解题思路:寻找字符串数组的最长公共前缀,将数组的第一个元素作为默认公共前缀,依次与后面的元素进行比较,取其公共部分,比较结束后,剩下的就是该字符串数组的最长公共前缀,示例代码如下: public clas

【LeetCode OJ 242】Valid Anagram

题目链接:https://leetcode.com/problems/valid-anagram/ 题目:Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", re

【LeetCode OJ 004】Median of Two Sorted Arrays

题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/ 题目:There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 解题思路:将两个有序数

【LeetCode OJ 328】Odd Even Linked List

题目链接:https://leetcode.com/problems/odd-even-linked-list/ 题目:Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to d

【LeetCode OJ 225】Implement Stack using Queues

题目链接:https://leetcode.com/problems/implement-stack-using-queues/ 题目:Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. empt

【LeetCode OJ 34】Search for a Range

题目链接:https://leetcode.com/problems/search-for-a-range/ 题目:Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not foun

【LeetCode OJ 232】Implement Queue using Stacks

题目链接:https://leetcode.com/problems/implement-queue-using-stacks/ 题目:Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the fro

【LeetCode OJ 237】Delete Node in a Linked List

题目链接:https://leetcode.com/problems/delete-node-in-a-linked-list/ 题目:Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the th