zoukankan      html  css  js  c++  java
  • same Tree

    Given two binary trees, write a function to check if they are equal or not.

    Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

    分析:注意边界条件的判断,先判断两树是不是为空,都为空,则为true,否则递归判断存在的其他情况,判断左右子树的情况。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSameTree(TreeNode *p, TreeNode *q) {
            if(p==NULL&&q==NULL)
                return true;
            else if(p&&q)
            {
                if(p->val==q->val)
                {
                    return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    };

     python:

    # Definition for a  binary tree node
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param p, a tree node
        # @param q, a tree node
        # @return a boolean
        def isSameTree(self, p, q):
            if p==None and q==None:
                return True
            elif p!=None and q==None:
                return False
            elif p==None and q!=None:
                return False
            elif p!=None and q!=None and p.val!=q.val:
                return False
            else:
                return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
  • 相关阅读:
    SA(后缀数组)专题总结
    LCT总结
    多项式全家桶
    fft.ntt,生成函数,各种数和各种反演
    P3939 数颜色
    P1879 [USACO06NOV]玉米田Corn Fields
    主席树模板
    P2633 Count on a tree
    P1972 [SDOI2009]HH的项链
    数论
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3572716.html
Copyright © 2011-2022 走看看