Symmetric Tree - Leetcode

来源:互联网 发布:网络制式 编辑:程序博客网 时间:2024/06/14 11:45

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

迭代版本:

/** * Definition for binary tree * 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;        Stack<TreeNode> s = new Stack<>();        s.push(root.left);        s.push(root.right);                while(!s.empty()){            TreeNode nd1 = s.pop();            TreeNode nd2 = s.pop();            if(nd1==null && nd2==null)               continue;            if(nd1==null || nd2==null)               return false;            if(nd1.val!=nd2.val)               return false;                        s.push(nd1.left); s.push(nd2.right);            s.push(nd1.right); s.push(nd2.left);        }        return true;    }}

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.


0 0
原创粉丝点击