• 【LeetCode】101. 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.

    提示:

    此题要求判断一个二叉树是否是左右对称的,且期望能够同时尝试一下迭代的方法和递归的方法。递归的方法相对来说简单一些,也更易读懂。迭代的方法需要利用栈来实现。

    代码:

    递归方法:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if (!root) return true;
            return childSymmetric(root->left, root->right);
        }
        
        bool childSymmetric(TreeNode* l, TreeNode* r) {
            if (!l && !r) return true;
            if (!l || !r) return false;
            return l->val == r->val && childSymmetric(l->left, r->right) && childSymmetric(l->right, r->left);
        }
    };

    迭代方法:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if (!root) return true;
            TreeNode *l, *r;
            stack<TreeNode*> s;
            if (root->left) {
                if (!root->right) return false;
                s.push(root->left);
                s.push(root->right);
            } else if (root->right) return false;
            
            while(!s.empty()) {
                l = s.top();s.pop();
                r = s.top();s.pop();
                if (l->val != r->val) return false;
                
                if (l->left) {
                    if (!r->right) return false;
                    s.push(l->left);
                    s.push(r->right);
                } else if (r->right) return false;
                
                if (l->right) {
                    if (!r->left) return false;
                    s.push(l->right);
                    s.push(r->left);
                } else if (r->left) return false;
            }
            return true;
        }
    };
  • 相关阅读:
    AQtime实战
    升级到 Fedora 12 后系统无法启动
    PostMortem Debugging Your Application with Minidumps and Visual Studio .NET
    分析、调试内存泄漏的应用程序
    中兴通讯有限公司 招聘“dotnet 高级工程师”
    快速构建大数据缓存
    【翻译 windbg 6】NET 调试示例实验 1:挂起
    【翻译 Windbg 5】.Net 调试举例
    【翻译 windbg 1】Getting started with windbg part I (第一部分 1)
    反汇编教程及汇编命令详解(一)
  • 原文地址:https://www.cnblogs.com/jdneo/p/4786926.html
Copyright © 2020-2023  润新知