劍指Offer的學習筆記(C#篇)-- 對稱的二叉樹

題目描述

請實現一個函數,用來判斷一顆二叉樹是否是對稱的。注意,若是一個二叉樹同此二叉樹的鏡像是一樣的,定義其爲對稱的。

一 . 題目分析

        遞歸法。函數

        1、空樹判斷,單獨搞出來。spa

        2、非空樹。code

               遞歸:一個遞歸+三個遞歸中止條件blog

二 . 代碼實現

class Solution
{
    public bool isSymmetrical(TreeNode pRoot)
    {
        // write code here
        //空樹斷定
        if (pRoot == null)
        {
            return true;
        }
        else
        //輸入根節點的左右節點
        {
            return helper(pRoot.left, pRoot.right);
        }
    }
     
    private bool helper(TreeNode n1, TreeNode n2)
    {
        //遞歸中止條件一:(對稱條件)、沒有子節點了!
        if(n1 == null && n2 == null)
            return true;
        //遞歸中止條件二:(非對稱條件)、左右節點只有一個是空的
        if(n1 == null || n2 == null)
            return false;
        //遞歸中止條件三:(非對稱條件)、左右對應節點不同
        if(n1.val != n2.val)
            return false;
        //遞歸方法
        return helper(n1.left, n2.right) && helper(n1.right, n2.left);
    }
}
相關文章
相關標籤/搜索