Leetcode - subtree-of-another-tree
Geeks4Geeks - check-if-the-given-binary-tree-have-a-subtree-with-equal-no-of-1s-and-0s

Leetcode - same-tree

violet posted @ Mar 06, 2020 05:19:07 AM in 算法 with tags Algorithm tree ruby Golang , 272 阅读

https://leetcode.com/problems/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.

 

There are many ways to check whether they're the same tree.

Method1: recursive

func isSameTree(t1 *TreeNode, t2 *TreeNode) bool {
    if (t1 == nil && t2 != nil) || (t1 != nil && t2 == nil) {
        return false
    }
    if t1 == nil && t2 == nil {
        return true
    }
    if t1.Val != t2.Val {
        return false
    }
   
    return isSameTree(t1.Left, t2.Left) && isSameTree(t1.Right, t2.Right)
}

 

def is_same_tree p, q
    if (p == nil && q != nil) || (p != nil && q == nil)
        return false
    end
    if p == nil && q == nil
        return true
    end
    if p.val != q.val
        return false
    end
    
    return is_same_tree(p.left, q.left) && is_same_tree(p.right, q.right)
end

Method2: in-order and pre-order to traversal two trees and see whether the orders are all the same

 

WB 7th Class Textbo 说:
Jul 14, 2023 06:20:04 PM

WB 7th Class Textbook Education is the West Bengal state Government Administered Autonomous Examining Authority are Published by English, Bengali Medium Textbooks from Standard 6th Addition, WBBSE Every Year Publish and Distribution WB 7th Class Textbook 2024 West Bengal Std 7th Class Textbook 2024 for High School Students Study Purpose,The Printed WB 7th Class Textbook 2024 are Distributed Through Cooperative Institutions All over Gujarat. Vendors are Linked to the Distribution of Textbooks with Distributors in each District. West Bengal Board Class Book 2024 are easily Accessible to All Students of This System.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter