Symmetric Binary Tree

Symmetric Binary Tree_第1张图片
Symmetric Binary Tree.png

解題思路 :

另外寫一個 function 一次放入兩個點來檢查 ( left and right child ) 裡面除了檢查兩個點的數值是否相同以外 另外 recursive 跑 (左子-> 左子, 右子->右子) 以及 (左子->右子, 右子->左子) 的組合是否都滿足相同的條件 都成立則回傳 true 否則判斷為 false

C++ code :


/**

  • Definition of TreeNode:
  • class TreeNode {
  • public:
  • int val;
    
  • TreeNode *left, *right;
    
  • TreeNode(int val) {
    
  •     this->val = val;
    
  •     this->left = this->right = NULL;
    
  • }
    
  • }
    */

class Solution {

public:
/**
* @param root, the root of binary tree.
* @return true if it is a mirror of itself, or false.
*/

bool help(TreeNode *left, TreeNode *right)
{
    if(left == nullptr && right == nullptr) return true;
    if(left == nullptr || right == nullptr) return false;
    if(left->val != right->val) return false;
    return help(left->left, right->right) && help(left->right, right->left);
}

bool isSymmetric(TreeNode* root) {
    // Write your code here
    if(root == nullptr) return true;
    return help(root->left, root->right);
}

};

你可能感兴趣的:(Symmetric Binary Tree)