101Symmetric Tree

来源:互联网 发布:云校排课软件怎么用 编辑:程序博客网 时间:2024/06/04 01:26

题目链接: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  3But the following is not:    1   / \  2   2   \   \   3    3Note:Bonus points if you could solve it both recursively and iteratively.

解题思路:
这题与 100 Same Tree 类似,都是考察二叉树的遍历。
这题稍微不同的是,比较的两棵树是根结点的左右子树。并且这两棵树的左右是相反的,这就要求在遍历的时候,其中一棵树必须把左边当右边,右边当左边。
题目要求我们用递归和非递归(迭代)的解法。
具体实施时,递归采用先序遍历,迭代采用层次遍历。

代码实现:
递归:

/** * 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 helper(root.left, root.right);    }    boolean helper(TreeNode p, TreeNode q) {        if(p == null && q == null)            return true;        if(p == null || q == null)            return false;        if(p.val != q.val)            return false;        return helper(p.left, q.right) && helper(p.right, q.left);    }}
192 / 192 test cases passed.Status: AcceptedRuntime: 1 ms

迭代:

/** * 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;        LinkedList<TreeNode> left = new LinkedList();        LinkedList<TreeNode> right = new LinkedList();        left.add(root.left);        right.add(root.right);        while(!left.isEmpty() && !right.isEmpty()) {            TreeNode leftNode = left.poll();            TreeNode rightNode = right.poll();            if(leftNode == null && rightNode == null)                continue;            if(leftNode == null || rightNode == null)                return false;            if(leftNode.val != rightNode.val)                return false;            left.add(leftNode.left);            left.add(leftNode.right);            right.add(rightNode.right);            right.add(rightNode.left);        }        if(!left.isEmpty() || !right.isEmpty())            return false;        return true;    }}
192 / 192 test cases passed.Status: AcceptedRuntime: 2 ms
0 0