leetcode--101. Symmetric Tree
阿新 • • 發佈:2017-08-31
win leet -- target 應該 efi iter int 開始
1、問題描述
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / 2 2 / \ / 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / 2 2 \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
2、邊界條件:root==null
3、思路:1)遞歸,對稱結構是鏡像;左手和右手的關系。所以應該左子樹和右子樹比較,右子樹和左子樹比較是否相同same。但是首先,從root開始分為左右子樹。
base case:左右都為空--true,左右有一個為空--false
2)叠代:一層一層的比較,可以利用隊列,前後取值比較是否相同。
4、代碼實現
1)遞歸
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * }*/ class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return isSameTree(root.left, root.right); } public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) {return true; } if (p == null || q == null) { return false; } return p.val == q.val && isSameTree(p.left, q.right) && isSameTree(p.right, q.left); } }
2)叠代
5、api
leetcode--101. Symmetric Tree