zoukankan      html  css  js  c++  java
  • LeetCode-Symmetric Tree

    树的遍历,

    递归:

     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 isSymmetric(TreeNode *root) {
    13         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         if (root == NULL)
    16             return true;
    17         return symmetric(root->left, root->right);
    18     }
    19     bool symmetric(TreeNode *lnode, TreeNode *rnode) {
    20         if (lnode == NULL && rnode == NULL)
    21             return true;
    22         if (lnode == NULL || rnode == NULL) 
    23             return false;
    24         if (lnode->val != rnode->val) {
    25             return false;
    26         }
    27         return symmetric(lnode->left, rnode->right) && symmetric(lnode->right, rnode->left);
    28     }
    29 };

    迭代要用到队列;

     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 isSymmetric(TreeNode *root) {
    13         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         if (root == NULL)
    16             return true;
    17         queue<TreeNode*> tqueue;
    18         tqueue.push(root->left);
    19         tqueue.push(root->right);
    20         while (!tqueue.empty()) {
    21             TreeNode *lnode = tqueue.front();
    22             tqueue.pop();
    23             TreeNode *rnode = tqueue.front();
    24             tqueue.pop();
    25             if (lnode == NULL && rnode == NULL)
    26                 continue;
    27             if (lnode == NULL || rnode == NULL || (lnode->val != rnode->val))
    28                 return false;
    29             tqueue.push(lnode->left);
    30             tqueue.push(rnode->right);
    31             tqueue.push(lnode->right);
    32             tqueue.push(rnode->left);
    33         }
    34         return true;
    35     }
    36 };
  • 相关阅读:
    Nginx开发从入门到精通
    Nginx配置文件(nginx.conf)配置详解
    转贝叶斯推断及其互联网应用(一):定理简介
    Vim 使用入门快捷键
    从贝叶斯定理说开去
    转特征值和特征向量
    第四章 特征值与特征向量
    numpy基础入门
    python range函数与numpy arange函数
    转悠望南山 Python闲谈(二)聊聊最小二乘法以及leastsq函数
  • 原文地址:https://www.cnblogs.com/chasuner/p/symmetic.html
Copyright © 2011-2022 走看看