LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Question:

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

For example, this binary tree is unsupported Ric:

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

But the following is not:

    1   / \  2   2   \   \   3    3

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

Ideas:

1) Recursion

package tree;public class SymmetricTree {    public boolean isSymmetric(TreeNode root) {        if (root == null) return true;        return isSymmetric(root.left, root.right);    }        private boolean isSymmetric(TreeNode left, TreeNode right) {        if (left == null && right == null) return true;        if (left == null || right == null) return false;        return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);    }}

2) iteration

package tree;import java.util.Stack;public class SymmetricTree {    public boolean isSymmetric(TreeNode root) {        if (root == null) return true;        Stack<TreeNode> stack1 = new Stack<TreeNode>();        Stack<TreeNode> stack2 = new Stack<TreeNode>();        TreeNode p = root.left;        TreeNode q = root.right;        while ((p != null && q != null) || (!stack1.isEmpty() && !stack2.isEmpty())) {            while (p != null && q != null) {                stack1.push(p);                p = p.left;                stack2.push(q);                q = q.right;            }                         if (p != null || q != null) return false;                        if (stack1.isEmpty() && stack1.isEmpty()) return true;            if (stack1.isEmpty() || stack1.isEmpty()) return false;                        TreeNode node1 = stack1.pop();            TreeNode node2 = stack2.pop();            if (node1.val != node2.val) return false;            p = node1.right;            q = node2.left;                    }                return p == null && q == null && stack1.isEmpty() && stack2.isEmpty();    }    }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.