遞歸法。函數
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); } }