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 };
  • 相关阅读:
    03--软件包管理工具 apt
    02--linux操作系统基础学习笔记
    01--vim常用快捷键
    00--Linux常用命令大全
    07 --C语言字符串函数
    06--C语言数学函数
    (备忘)Rect和RectF的区别
    在android程序中加入widget(窗口小部件)并与之交互的关键代码
    (原)android的alertdialog中加入edittext但是不弹出软键盘等问题的解决与原因
    (转)dp和dip是同一个单位
  • 原文地址:https://www.cnblogs.com/chasuner/p/symmetic.html
Copyright © 2011-2022 走看看