Leetcode-101. Symmetric Tree

本文介绍了一种判断二叉树是否对称的方法,通过递归和非递归两种方式实现了算法,并提供了详细的代码示例。对于递归方法,通过对左右子树进行对比来判断对称性;对于非递归方法,则利用两个栈来辅助实现。

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

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

这个题目用非递归的就是用堆来实现,居然还有Bonus。 Your runtime beats 23.40% of java submissions.

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        
	if(root == null) return true;
	
	return isSymmetric(root.left,root.right);
    }

    public boolean isSymmetric(TreeNode root1,TreeNode root2){

	if(root1 == null && root2 == null) return true;
	
	if(root1 != null && root2 != null){
		boolean flag = root1.val == root2.val;
		if(flag) flag = isSymmetric(root1.left,root2.right);
		if(flag) flag = isSymmetric(root1.right,root2.left);
		return flag;
	}

	return false;
	
    }
}
然并卵,不知道怎么体现的。 Your runtime beats 4.64% of java submissions.

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

	Stack<TreeNode> stack1 = new Stack<TreeNode>();
	Stack<TreeNode> stack2 = new Stack<TreeNode>();
	stack1.push(root.left);stack2.push(root.right);
	boolean flag = true;
	while(!stack1.empty() && !stack2.empty()){

		TreeNode root1 = stack1.pop();
		TreeNode root2 = stack2.pop();
		if( root1 != null && root2 != null){
			if(root1.val != root2.val){flag = false;break;}
			else{
				stack1.push(root1.right);
				stack1.push(root1.left);
				stack2.push(root2.left);
				stack2.push(root2.right);
			}
		}else if(root1 == null && root2 == null) continue;
		else{flag = false; break;}
	}
	
	if(flag){
		if(!stack1.empty() || !stack2.empty()) flag = false;
	}
	
	return flag;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值