問題描述
請實現一個函數,用來判斷一顆二叉樹是不是對稱的。注意,如果一個二叉樹同此二叉樹的鏡像是同樣的,定義其爲對稱的。
思路
方法一,再新建一棵樹,新建的時候就把它建立成鏡像的。 然後判定這兩棵樹是不是同一棵樹就OK。這樣要遍歷兩次。還要浪費O(n)的空間。
方法二,就直接判斷樹是不是鏡像的。把圖畫出來看看就能理解代碼了。
方法一
class Solution {
TreeNode root;
boolean isSymmetrical(TreeNode pRoot) {
if(pRoot == null) return true;
if(pRoot.left == null && pRoot.right == null) return true;
this.root = generateNewTree(pRoot);
return isSame(pRoot,root);
}
private TreeNode generateNewTree(TreeNode p){
if(p == null) return null;
TreeNode tmp = new TreeNode(p.val);
tmp.left = generateNewTree(p.right);
tmp.right = generateNewTree(p.left);
return tmp;
}
private boolean isSame(TreeNode ori, TreeNode mir){
if(ori == null && mir == null) return true;
if(ori == null || mir == null) return false;
if(ori.val != mir.val) return false;
return isSame(ori.left,mir.left) && isSame(ori.right,mir.right);
}
}
方法二
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);
}
}
方法三
非遞歸算法。成雙成對的入棧,出棧即可。
import java.util.*;
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
if(pRoot == null || pRoot.left == null && pRoot.right == null) return true;
if(pRoot.left == null || pRoot.right == null) return false;
if(pRoot.left.val != pRoot.right.val) return false;
Stack<TreeNode> stack = new Stack<>();
stack.push(pRoot.left); stack.push(pRoot.right);
while(!stack.isEmpty()){
TreeNode first = stack.pop(), second = stack.pop();
if(first.val != second.val) return false;
if(first.left == null && second.right != null) return false;
if(first.left != null && second.right == null) return false;
if(first.left != null && second.right != null){
stack.push(first.left);
stack.push(second.right);
}
if(first.right == null && second.left != null) return false;
if(first.right != null && second.left == null) return false;
if(first.right != null && second.left != null){
stack.push(first.right);
stack.push(second.left);
}
}
return true;
}
}