Try   HackMD

【LeetCode】 101. Symmetric Tree

Description

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

給一棵二元樹,請檢查它的鏡像是否和自己相等。(以中間為軸對稱)

Example:

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

Solution

  • 可以直接做一個製造鏡像樹的function,不過那樣太浪費空間了。
  • 因此我們採取直接比較左子樹和右子樹的策略,比較完值確認相等之後(要注意null的情況),再去比較它們的子樹。
    • 左子樹的左子樹要和右子樹的右子樹相等;左子樹的右子樹要和右子樹的左子樹相等。

Code

/** * 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 isOpposite(TreeNode* left,TreeNode* right) { if(!left && !right) return true; if(!left && right) return false; if(left && !right) return false; if(left->val != right->val) return false; return isOpposite(left->left,right->right) && isOpposite(left->right,right->left); } bool isSymmetric(TreeNode* root) { if(!root) return true; return isOpposite(root->left,root->right); } };
tags: LeetCode C++