# 101. Symmetric Tree

## 1.問題&#x20;

* 給予一個binary tree, 判斷是否為對稱

![](/files/-LOSXHJR-RQAxeLZSNpp)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意:  root是NULL是true或false?
* function header, parameter
* test input
* 說明想法
  * 將root複製出一份左右對稱的樹後, 比較root 與該數是否是same tree
* 測試計算複雜度
  * recursive的runtime是計算total call number
    * deepCopy
    * swap
    * isSameTree

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (!root) { 
            return true;
        }
        
        TreeNode* copy = deepCopy(root);
        TreeNode* swapNode = swap(copy);
        return isSameTree(root, swapNode);
    }
private:
    TreeNode* deepCopy(TreeNode* node){
        if (!node) {
            return NULL;
        }
        TreeNode* newNode = new TreeNode(node->val);
        newNode->left = deepCopy(node->left);
        newNode->right = deepCopy(node->right);
        return newNode;
    }
    
    TreeNode* swap(TreeNode* node){
        if (!node) {
            return NULL;
        }
        
        node->left = swap(node->left);
        node->right = swap(node->right);
        TreeNode* tmp = node->left;
        node->left = node->right;
        node->right = tmp;
        return node;
    }
    
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (!p && !q) {
            return true;
        } 
        
        if (!p || !q) {
            return false;
        } 
        
        if (p->val == q->val) {
            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
        
        return false;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/101.-symmetric-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
