美文网首页
Symmetric Binary Tree

Symmetric Binary Tree

作者: 一枚煎餅 | 来源:发表于2016-09-19 05:56 被阅读0次
Symmetric Binary Tree.png

解題思路 :

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

C++ code :

<pre><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

      本文链接:https://www.haomeiwen.com/subject/xmwgettx.html