
這題需要判斷二元樹是否是對稱的。
LeetCode 題目連結
https://leetcode.com/problems/symmetric-tree/
題目
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
Accept 作法
Runtime: 0 ms
Memory: 37.7 MB
Java 程式碼
- class Solution {
- public boolean isSymmetric(TreeNode root) {
- return is_Symmetric(root,root);
- }
- public boolean is_Symmetric(TreeNode leftRoot,TreeNode rightRoot) {
- if(leftRoot == null && rightRoot!=null){
- return false;
- }
- if(leftRoot != null && rightRoot==null){
- return false;
- }
- if(leftRoot == null && rightRoot == null)
- return true;
- return (leftRoot.val == rightRoot.val) && is_Symmetric(leftRoot.left,rightRoot.right) && is_Symmetric(leftRoot.right,rightRoot.left);
- }
- }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。

沒有留言:
張貼留言