Easy 101题 Symmetric Tree

来源:互联网 发布:php 私有方法 编辑:程序博客网 时间:2024/05/17 01:21

Question:

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.


Solution:

/** * Definition for a binary tree node. * public 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;        return isSymmetric(root.left,root.right);    }    public boolean isSymmetric(TreeNode left,TreeNode right){        if(left==null||right==null)            return right==left;        if(left.val!=right.val)            return false;        return isSymmetric(left.left,right.right)&&isSymmetric(left.right,right.left);    }    }

STACK做法

/** * Definition for a binary tree node. * public 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;        if((root.left==null&&root.right!=null)||(root.left!=null&&root.right==null))            return false;        if(root.left==null&&root.right==null)            return true;        Stack<TreeNode> s=new Stack<TreeNode>();        s.push(root.left);        s.push(root.right);                while(!s.isEmpty())        {            if(s.size()%2!=0)   return false;            TreeNode right = s.pop();            TreeNode left = s.pop();                        if(right.val!=left.val)                return false;                        if((left.left==null&&right.right!=null)||(left.left!=null&&right.right==null))            {                return false;            }            if(!(left.left==null&&right.right==null))            {                    s.push(left.left);                s.push(right.right);            }                        if((right.left==null&&left.right!=null)||(right.left!=null&&left.right==null))            {                return false;            }            if(!(right.left==null&&left.right==null))            {                s.push(right.left);                s.push(left.right);            }        }        return true;        }    }



0 0
原创粉丝点击