對稱二叉樹(遞歸+迭代)

題目

給定一個二叉樹,檢查它是否是鏡像對稱的。

例如,二叉樹 [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;
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章