[leetcode]Symmetric Tree

有意思的是还要写非递归版本。

这是递归版本:

public class Solution {

    public boolean isSymmetric(TreeNode root) {

        // Start typing your Java solution below

        // DO NOT write main() function

        if (root == null) return true;

        return (isMirror(root.left, root.right));

    }

    

    public boolean isMirror(TreeNode p, TreeNode q) {

        if (p == null && q == null) return true;

        if (p != null && q != null &&

            q.val == p.val &&

            isMirror(p.left, q.right) &&

            isMirror(p.right, q.left)) {

            return true;

        }

            

        return false;

    }

}

非递归版本。

public class Solution {

    public boolean isSymmetric(TreeNode root) {

        // Start typing your Java solution below

        // DO NOT write main() function

        

        if (root == null) return true;

        if (root.left == null && root.right == null) return true;

        if (root.left == null || root.right == null) return false;

        

        LinkedList<TreeNode> lq = new LinkedList<TreeNode>();

        LinkedList<TreeNode> rq = new LinkedList<TreeNode>();

        

        lq.offer(root.left);

        rq.offer(root.right);

        

        while (lq.size() != 0 && rq.size() != 0) {

            TreeNode ln = lq.poll();

            TreeNode rn = rq.poll();

            

            if (ln == null && rn == null) continue;

            if (ln == null || rn == null) return false;

            if (ln.val != rn.val) return false;

            

            lq.offer(ln.left);

            lq.offer(ln.right);

            rq.offer(rn.right);

            rq.offer(rn.left);

        }

        

        return true;

    }

}

  

你可能感兴趣的:(LeetCode)