对称二叉树(递归+迭代)

题目

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

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

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

递归

写一个递归函数,当且仅当两个节点的值相等且节点的孩子也对称的时候返回true

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        return dfs(root.left, root.right);
    }
    
    public boolean dfs(TreeNode root1, TreeNode root2) {
        if ((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false;
        else if (root1 != null && root2 != null) {
            return root1.val == root2.val
                && dfs(root1.left, root2.right)
                && dfs(root1.right, root2.left);
        }
        return true;
    }
    
}

迭代

迭代的思路就是层次遍历,最开始将根节点入队两次,然后每次出队两个节点AB,比较两个节点。若不同时为空或者值不相等,说明不是镜像;若相等,将节点A的左孩子与节点B的右孩子一起入队,将节点A的右孩子与节点B的左孩子一起入队。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public boolean isSymmetric(TreeNode root) {
        
        LinkedList<TreeNode> que = new LinkedList<>();
        que.addLast(root);
        que.addLast(root);
        
        while (!que.isEmpty()) {
            TreeNode root1 = que.removeFirst();
            TreeNode root2 = que.removeFirst();
            
            if (root1 == null && root2 == null) continue;
            else if (root1 != null && root2 != null && root1.val == root2.val) {
                que.addLast(root1.left);
                que.addLast(root2.right);
                que.addLast(root2.left);
                que.addLast(root1.right);
            }
            else return false;
        }
        
        return true;
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章