• 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)
  • 相关阅读:
    Zookeeper服务器启动
    BeanFactoryPostProcessor
    ZK简介
    自定义标签解析
    高性能MySQL
    Redis原理
    ApplicationContext
    ThreadPoolExecutor
    NW.js构建PC收银端安装程序的指南
    NW.js安装原生node模块node-printer控制打印机
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3572716.html
Copyright © 2020-2023  润新知