zoukankan      html  css  js  c++  java
  • Lintcode---等价二叉树

    检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。

    样例
        1             1
       /            / 
      2   2   and   2   2
     /             /
    4             4
    

    就是两棵等价的二叉树。

        1             1
       /            / 
      2   3   and   2   3
     /               
    4                 4
    

    就不是等价的。

    思路:

    还是用递归的方法,先序遍历二叉树;

    当根节点相等时,且左右子树均为等价二叉树时,该二叉树为等价二叉树;

    否则,不是等价二叉树;

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @aaram a, b, the root of binary trees.
         * @return true if they are identical, or false.
         */
        /*
        思路:还是用递归的方法,分情况进行比较;
        当根节点相等时,且左右子树均为等价二叉树时,该二叉树为等价二叉树;
        */
        bool isIdentical(TreeNode* a, TreeNode* b) {
            // Write your code here
            if(a==NULL&&b==NULL){
                return true;
            }
            if(a==NULL&&b!=NULL){
                return false;
            }
            if(a!=NULL&&b==NULL){
                return false;
            }
            
            if(a!=NULL&&b!=NULL&&(a->val==b->val)){
                if(isIdentical(a->left,b->left)&&isIdentical(a->right,b->right)){
                    return true;
                }
                else{
                    return false;
                }
            }
            else{
                return false;
            }
        }
    };
    
  • 相关阅读:
    SVD与PCA
    Service(二):通信
    Service(一):认识service、绑定Service
    计划(四)
    Android studio 安装过程中遇到的问题
    UFLDL 教程学习笔记(四)
    opencv之dft及mat类型转换
    《第一行代码》(四)
    《第一行代码》
    计划(三)
  • 原文地址:https://www.cnblogs.com/Allen-rg/p/7065895.html
Copyright © 2011-2022 走看看