博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] Same Tree
阅读量:4561 次
发布时间:2019-06-08

本文共 2583 字,大约阅读时间需要 8 分钟。

Same Tree 题解

原创文章,拒绝转载

题目来源:


Description

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

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

Example

Example 1:

Input:     1         1          / \       / \         2   3     2   3        [1,2,3],   [1,2,3]Output: true

Example 2:

Input:     1         1          /           \         2             2        [1,2],     [1,null,2]Output: false

Example 3:

Input:     1         1          / \       / \         2   1     1   2        [1,2,1],   [1,1,2]Output: false

Solution

class Solution {private:    bool isSameNode(TreeNode* node1, TreeNode* node2) {        if (node1 == NULL && node2 == NULL)            return true;        if (node1 != NULL && node2 != NULL) {            return (node1 -> val == node2 -> val) &&                    isSameNode(node1 -> left, node2 -> left) &&                    isSameNode(node1 -> right, node2 -> right);        } else {            return false;        }    }public:    bool isSameTree(TreeNode* node1, TreeNode* node2) {        return isSameNode(node1, node2);    }};

解题描述

这道题是要判断给出的两棵二叉树是否完全相等,也就是判断两棵树是不是结构完全相同而且每个节点的数字是否完全一样。一开始我想到的还是简单的递归做法,也就是上面给出来的。不过跑出来的时间确实还是比较长。

AC之后看了讨论区,发现还是可以用非递归的方式来解决的。主要是使用栈来模拟递归调用,跑出来的时间也确实缩短了一些:

class Solution {public:    bool isSameTree(TreeNode* node1, TreeNode* node2) {        if (node1 == NULL && node2 == NULL)            return true;        if (node1 != NULL && node2 != NULL) {            stack
stack1; stack
stack2; stack1.push(node1); stack2.push(node2); TreeNode *n1, *n2; while (!stack1.empty() && !stack2.empty()) { n1 = stack1.top(); stack1.pop(); n2 = stack2.top(); stack2.pop(); if (n1 -> val != n2 -> val) return false; if (n1 -> left != NULL) stack1.push(n1 -> left); if (n2 -> left != NULL) stack2.push(n2 -> left); if (stack1.size() != stack2.size()) return false; if (n1 -> right != NULL) stack1.push(n1 -> right); if (n2 -> right != NULL) stack2.push(n2 -> right); if (stack1.size() != stack2.size()) return false; } return stack1.size() == stack2.size(); } else { return false; } }};

转载于:https://www.cnblogs.com/yanhewu/p/8330417.html

你可能感兴趣的文章
extjs grid renderer用法
查看>>
vue 如何在循环中绑定v-model
查看>>
shell脚本
查看>>
[代码笔记]JS保持函数单一职责,灵活组合
查看>>
推荐工具,AnkhSvn
查看>>
cmd 重定向
查看>>
【IOS开发】如何画1像素的线
查看>>
Android 的 Button 按钮实现的两种方式
查看>>
【计算机视觉】双目测距(五)--匹配算法对比
查看>>
Ajax读取XML和JSON数据
查看>>
KMP模板
查看>>
luogu 1314 聪明的质检员
查看>>
[转载]求职者防骗必读!楼主亲身经历告诉你岗前培训多么不靠谱而且违法!
查看>>
Hibernate内存溢出分析一例
查看>>
基于Axis1.4的webservice接口开发(接口调用)
查看>>
Hive内置函数详解
查看>>
【转】MyEclipse快捷键大全
查看>>
IT职业技能图谱10--Hadoop家族技能图谱
查看>>
Java - 反射(1)
查看>>
控制台中显示执行的Sql语句
查看>>