【Leetcode】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

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

思路:

注意我在递归中保存结果的方式,跟Kth Smallest Element in a BST 算法2和Balanced Binary Tree 中是一样的。

基本框架是:

	boolean result = true;
	public boolean recur(TreeNode root){
		if(root!=null){
			if(satisfy a condition){
				result = false;
			}
			recur(root.left);
			recur(root.right);
		}
		return result;
	}


算法:

	public boolean isSym(TreeNode p, TreeNode q) {
		if (p == null && q == null) {//都为空
			return true;
		}else if (p == null || q == null) {//有一个不为空
			result = false;
		}else if (p.val == q.val) {
			isSym(p.left, q.right);//注意对称
			isSym(p.right, q.left);
		} else {
			result = false;
		}
		return result;
	}

	public boolean isSymmetric(TreeNode root) {
		if (root == null) { 
			return true;
		}
		if (root.left == null && root.right == null) { //单结点
			return true;
		}
		if (root.left == null || root.right == null) {//不对称
			return false;
		}
		return isSym(root.left, root.right); 
	}

	boolean result = true;


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeqiuzs/article/details/49964621
个人分类: leetcode
所属专栏: Leetcode题解java版
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

【Leetcode】Symmetric Tree

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭