zoukankan      html  css  js  c++  java
  • 【Leetcode】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.

    思路:可以分别把树先序和中序遍历到两个数组,然后比较遍历序列,但空间复杂度比较大。更直接的方法是使用递归判断,即先判断根结点是否相等,然后判断左右子树是否分别相等,代码如下,时间复杂度为O(n),n为树中结点数,空间复杂度为O(k),k为树高。

    /**
     * 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) 
    	{
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
    		// 空树相等
    		if (!p && !q)
    			return true;
    
    		// 只有其中一个为空树,或者结点值不一样,则不相等
            if ((p&&!q) || (!p&&q) || p->val != q->val)
    			return false;
    
    		// 判断子树是否相等
    		return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
        }
    };




  • 相关阅读:
    我是一条内存[转]
    随机翻唱辑 [2006.8.18更新]
    CentOS NTFS 挂载
    grub备忘
    CentOS 使用163软件源
    被车撞了
    爱上苦瓜
    无聊的游戏
    今天去爬山了
    博客搬家了:www.sanv.org
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3329215.html
Copyright © 2011-2022 走看看