/** 請實現一個函數,用來判斷一顆二叉樹是否是對稱的。 注意,若是一個二叉樹同此二叉樹的鏡像是一樣的,定義其爲對稱的 */
思路:java
/** 1.只要pRoot.left和pRoot.right是否對稱便可 2.左右節點的值相等且對稱子樹left.left, right.right; left.rigth,right.left也對稱 */
代碼:函數
import java.util.*; public class Solution { boolean isSymmetrical(TreeNode pRoot){ if(pRoot == null) return true; return isSymmetrical(pRoot.left, pRoot.right); } private boolean isSymmetrical(TreeNode left, TreeNode right) { if(left == null && right == null) return true; if(left == null || right == null) return false; return left.val == right.val //爲鏡像的條件:左右節點值相等 && isSymmetrical(left.left, right.right) //2.對稱的子樹也是鏡像 && isSymmetrical(left.right, right.left); } }
思路spa
/* * DFS使用stack來保存成對的節點 * 1.出棧的時候也是成對的 , 1.若都爲空,繼續; 2.一個爲空,返回false; 3.不爲空,比較當前值,值不等,返回false; * 2.肯定入棧順序,每次入棧都是成對成對的,如left.left, right.right ;left.rigth,right.left */
代碼code
import java.util.*; public class Solution { boolean isSymmetrical(TreeNode pRoot){ return isSymmetricalDFS(pRoot); } boolean isSymmetricalDFS(TreeNode pRoot){ if(pRoot == null) return true; Stack<TreeNode> s = new Stack<>(); s.push(pRoot.left); s.push(pRoot.right); while(!s.empty()) { TreeNode right = s.pop();//成對取出 TreeNode left = s.pop(); if(left == null && right == null) continue; if(left == null || right == null) return false; if(left.val != right.val) return false; //成對插入 s.push(left.left); s.push(right.right); s.push(left.right); s.push(right.left); } return true; }
}
思路:blog
/* * BFS使用Queue來保存成對的節點,代碼和上面極其類似 * 1.出隊的時候也是成對成對的 1.若都爲空,繼續; 2.一個爲空,返回false; 3.不爲空,比較當前值,值不等,返回false; * 2.肯定入隊順序,每次入隊都是成對成對的,如left.left, right.right ;left.rigth,right.left */
代碼遞歸
import java.util.*; public class Solution { boolean isSymmetrical(TreeNode pRoot){ return isSymmetricalBFS(pRoot); } boolean isSymmetricalBFS(TreeNode pRoot) { if(pRoot == null) return true; Queue<TreeNode> s = new LinkedList<>(); s.offer(pRoot.left); s.offer(pRoot.right); while(!s.isEmpty()) { TreeNode left= s.poll();//成對取出 TreeNode right= s.poll(); if(left == null && right == null) continue; if(left == null || right == null) return false; if(left.val != right.val) return false; //成對插入 s.offer(left.left); s.offer(right.right); s.offer(left.right); s.offer(right.left); } return true; }}