前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Tree - 100. Same Tree

Tree - 100. Same Tree

作者头像
ppxai
发布2020-09-23 17:24:25
4810
发布2020-09-23 17:24:25
举报
文章被收录于专栏:皮皮星球皮皮星球

100. Same Tree

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 1:

代码语言:javascript
复制
Input:  
           1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

思路:

题目很简单,判断两个树是否相同,只要随便使用一种方式遍历一次树就可以,这里使用先序遍历来做。

代码:

go:

代码语言:javascript
复制
/**

 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

//recursive
func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }
    if (p == nil && q != nil) || (p != nil && q == nil) {
        return false
    }
    
    if p.Val != q.Val {
        return false
    } else {
        return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
    }
}

/* iteratively
func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }
    if (p == nil && q != nil) || (p != nil && q == nil) {
        return false
    }
    
    stackp := list.New()
    stackq := list.New()
    stackp.PushBack(p)
    stackq.PushBack(q)
    for stackp.Len() != 0 || stackq.Len() != 0 {
        ep, eq := stackp.Back(), stackq.Back()
        stackp.Remove(ep)
        stackq.Remove(eq)
        curp, curq := ep.Value.(*TreeNode), eq.Value.(*TreeNode)
        if curp.Val != curq.Val {
           return false 
        }
        
        if curp.Left != nil && curq.Left != nil{
            stackp.PushBack(curp.Left)
            stackq.PushBack(curq.Left)
        } else if curp.Left == nil && curq.Left == nil {
            
        } else {
            return false
        }
        
        if curp.Right != nil && curq.Right != nil{
            stackp.PushBack(curp.Right)
            stackq.PushBack(curq.Right)
        } else if curp.Right == nil && curq.Right == nil {
            
        } else {
            return false
        }
        
    }
    
    return true
}
*/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年08月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档