zoukankan      html  css  js  c++  java
  • 剑指offer-面试题28-对称的二叉树-二叉树递归

    /*
    题目:
    	判断给定的二叉树是否对称。
    */
    /*
    思路:
    	1、递归法。
    	2、基础条件:两棵树均为空为true;一棵树为空,一棵树不为空,为false;两棵树的根节点值不同,为false。
    	3、其它:判断树1的左子树和树2的右子树是否对称,判断树1的右子树和树2的左子树是否对称。
    */
    #include<iostream>
    #include<string.h>
    #include<algorithm>
    #include<cmath>
    #include<stdio.h>
    using namespace std;
    
    struct BinaryTreeNode {
    	int val;
    	BinaryTreeNode* left;
    	BinaryTreeNode* right;
    	BinaryTreeNode(int x) :
    			val(x), left(NULL), right(NULL) {
    	}
    };
    
    bool isSymmetrical(BinaryTreeNode* pRoot1,BinaryTreeNode* pRoot2){
        if(pRoot1 == nullptr && pRoot2 == nullptr){
            return true;
        }
        if(pRoot1 == nullptr || pRoot2 == nullptr) return false;
    
        bool flag = false;
        if(pRoot1->val == pRoot2->val){
            flag = isSymmetrical(pRoot1->left,pRoot2->right) && isSymmetrical(pRoot1->right,pRoot2->left);
        }
        return flag;
    }
    
    bool isSymmetrical(BinaryTreeNode* pRoot){
        if(pRoot == nullptr) return false;
        return isSymmetrical(pRoot->left,pRoot->right);
    }
    
    
    int main(){
       BinaryTreeNode* node1 = new BinaryTreeNode(8);
       BinaryTreeNode* node2 = new BinaryTreeNode(6);
       BinaryTreeNode* node3 = new BinaryTreeNode(6);
       BinaryTreeNode* node4 = new BinaryTreeNode(5);
       BinaryTreeNode* node5 = new BinaryTreeNode(7);
       BinaryTreeNode* node6 = new BinaryTreeNode(7);
       BinaryTreeNode* node7 = new BinaryTreeNode(5);
       node1->left = node2;
       node1->right = node3;
       node2->left = node4;
       node2->right = node5;
       node3->left = node6;
       node3->right = node7;
    
       cout<<isSymmetrical(node1)<<endl;
    }
    

       

  • 相关阅读:
    【待补充】Spark 集群模式 && Spark Job 部署模式
    Spark 集群管理命令
    Spark job 部署模式
    [Spark Core] Spark 核心组件
    [Spark RDD_1] RDD 基本概念
    【读书笔记】《天才在左 疯子在右》
    [Spark Core] Spark 使用第三方 Jar 包的方式
    [Spark Core] 在 Spark 集群上运行程序
    【待补充】[Spark Core] Spark 实现标签生成
    Spark 集群搭建
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11930104.html
Copyright © 2011-2022 走看看