zoukankan      html  css  js  c++  java
  • 1368:对称二叉树(tree_c)

    【题目描述】

    如果二叉树的左右子树的结构是对称的,即两棵子树皆为空,或者皆不空,则称该二叉树是对称的。编程判断给定的二叉树是否对称.

    例:如下图中的二叉树T1是对称的,T2是不对称的。

    二叉树用顺序结构给出,若读到#则为空,二叉树T1=ABCDE,T2=ABCD#E,如果二叉树是对称的,输出“Yes”,反之输出“No”。

    【输入】

    二叉树用顺序结构给出,若读到#则为空。

    【输出】

    如果二叉树是对称的,输出“Yes”,反之输出“No”。

    【输入样例】

    ABCDE

    【输出样例】

    Yes

    #include <bits/stdc++.h>
    using namespace std;
    
    struct Node {
        char value;
        Node *left, *right;
    };
    
    Node *CreateTree(const string &s, int i)
    {
        if (i < 0 || i >= s.size() || s[i] == '#') {
            return NULL;
        } else {
            // cout << i << endl;
            Node *root = new Node;
            root->value = s[i];
            root->left = root->right = NULL;
            root->left = CreateTree(s, i * 2 + 1);
            root->right = CreateTree(s, i * 2 + 2);
            return root;
        }
    }
    
    string PreOrder(Node *root)
    {
        string s;
        if (root != NULL) {
            s.push_back(root->value);
            s += PreOrder(root->left);
            s += PreOrder(root->right);
        }
        return s;
    }
    
    string InOrder(Node *root)
    {
        string s;
        if (root != NULL) {
            s += InOrder(root->left);
            s.push_back(root->value);
            s += InOrder(root->right);
        }
        return s;
    }
    
    string PostOrder(Node *root)
    {
        string s;
        if (root != NULL) {
            s += PostOrder(root->left);
            s += PostOrder(root->right);
            s.push_back(root->value);
        }
        return s;
    }
    
    bool sym(Node *root)
    {
        if (root == NULL) {
            return true;
        } else if (!sym(root->left)) {
            return false;
        } else if (!sym(root->right)) {
            return false;
        } else if (root->left == NULL && root->right == NULL) {
            return true;
        } else if (root->left != NULL && root->right != NULL) {
            return true;
        } else {
            return false;
        }
    }
    
    
    int main()
    {
        // freopen("1.txt", "r", stdin);
        string s = "ABCDE";
        cin >> s;
        Node *root = CreateTree(s, 0);
        // cout << PreOrder(root) << endl;
        // cout << InOrder(root) << endl;
        // cout << PostOrder(root) << endl;
        cout << (sym(root) ? "Yes" : "No");
        return 0;
    }
  • 相关阅读:
    linux安装jdk
    maven工程直接部署在tomcat上
    将maven工程转成dynamic web project
    史上最全最强SpringMVC详细示例实战教程
    06-spring框架—— Spring 与Web
    05-spring框架—— Spring 事务
    04-spring框架—— Spring 集成 MyBatis
    03-spring框架—— AOP 面向切面编程
    01-spring框架——spring概述
    我对于语言只是工具的理解和感悟
  • 原文地址:https://www.cnblogs.com/gaojs/p/14947769.html
Copyright © 2011-2022 走看看