zoukankan      html  css  js  c++  java
  • [LeetCode] Symmetric Tree

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

    For example, this binary tree is symmetric:

        1
       / \
      2   2
     / \ / \
    3  4 4  3
    

    But the following is not:

        1
       / \
      2   2
       \   \
       3    3
    

    Note:
    Bonus points if you could solve it both recursively and iteratively.

    递归,保存左右两个节点,然后判断leftNode->left和rightNode->right,以及leftNode->right和rightNode->left。如此不断递归

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool check(TreeNode *leftNode, TreeNode *rightNode)
    13     {
    14         if (leftNode == NULL && rightNode == NULL)
    15             return true;
    16             
    17         if (leftNode == NULL || rightNode == NULL)
    18             return false;
    19             
    20         return leftNode->val == rightNode->val && check(leftNode->left, rightNode->right) && 
    21             check(leftNode->right, rightNode->left);
    22     }
    23     
    24     bool isSymmetric(TreeNode *root) {
    25         // Start typing your C/C++ solution below
    26         // DO NOT write int main() function
    27         if (root == NULL)
    28             return true;
    29             
    30         return check(root->left, root->right);
    31     }
    32 };
  • 相关阅读:
    希尔伯特空间
    Java基础之类型转换总结篇
    超实用在线编译网站,编辑器
    3269: 万水千山粽是情
    Problem A: 李白打酒
    2370: 圆周率
    C语言fmod()函数:对浮点数取模(求余)
    C语言exp()函数:e的次幂函数(以e为底的x次方值)
    2543: 数字整除
    2542: 弟弟的作业
  • 原文地址:https://www.cnblogs.com/chkkch/p/2772230.html
Copyright © 2011-2022 走看看