[leetcode]symmetric-tree
阿新 • • 發佈:2018-11-12
題目描述:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
思路:
判斷一棵樹是否為映象的,首先判斷其是否為空,若為空也是映象。若不為空,呼叫函式來判斷左右子樹是否滿足映象。判斷左右子樹是否滿足映象的函式有兩個節點的引數,若兩個節點啊都為null,返回true;若其中有一個為null,返回false;若兩節點的val值相等,返回節點1左子樹和節點2右子樹是否為映象和節點1右子樹和節點2左子樹是否為映象的結果的&&結果,否則返回false。
程式碼:
public class Solution { public boolean isSymmetric(TreeNode root) { if(root==null){ return true; } return isSymmetric(root.left,root.right); } public boolean isSymmetric(TreeNode l,TreeNode r){ if(l==null&&r==null){ return true; } if(l==null||r==null){ return false; } if(l.val==r.val){ return isSymmetric(l.left,r.right)&&isSymmetric(l.right,r.left); } return false; } }