LeetCode 872. Leaf-Similar Trees

2026. 1. 24. 22:28·코딩테스트/LeetCode

872. Leaf-Similar Trees

 

Problem


Solution

The key requirement of this problem is as follows:

  1. Return True if the leaf of sequences of root1 and root2 are the same otherwise return False.

To satisfy this requirement, I used a preorder traversal with a stack.

 

Since we need to process two binary trees, I created a helper function getLeaves.

 

First, initialize stack as a list containing root, and set leaves as an empty list.

 

If root is None, return leaves because the tree is empty.

 

While stackis not empty, do the following steps:

  1. Pop the last node from stack.
  2. If the current node has no left and right children, append its value to leaves.
  3. Otherwise, if the node has a right child, append it to stack.
  4. If the node has a left child, append it to stack.

By pushing the right child first, the left subtree is processed first.

This keeps the leaf order consistent with a preorder traversal.

 

At the end of the loop, return the leaves.

 

Outside of getLeaves, call it for both trees and compare the results.
If both leaf lists are the same, return True otherwise return False.

 

class Solution(object):
    def leafSimilar(self, root1, root2):
        def getLeaves(root):
            stack = [root]
            leaves = []
            if not stack:
                return leaves

            while stack:
                node = stack.pop()
                if not node.left and not node.right:
                    leaves.append(node.val)
                else:
                    if node.right:
                        stack.append(node.right)
                    if node.left:
                        stack.append(node.left)

            return leaves

        tree1 = getLeaves(root1)
        tree2 = getLeaves(root2)
        return tree1 == tree2

 


 

https://github.com/K-MarkLee/LeetCode-Practice

 

GitHub - K-MarkLee/LeetCode-Practice: A collection of LeetCode questions to ace the coding interview! - Created using [LeetHub 2

A collection of LeetCode questions to ace the coding interview! - Created using [LeetHub 2.0](https://github.com/maitreya2954/LeetHub-2.0-Firefox) - K-MarkLee/LeetCode-Practice

github.com

 

저작자표시 비영리 변경금지 (새창열림)

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode 1448. Count Good Nodes in Binary Tree  (0) 2026.01.25
LeetCode 104. Maximum Depth of Binary Tree  (0) 2026.01.24
LeetCode 2130. Maximum Twin Sum of a Linked List  (0) 2026.01.23
LeetCode 206. Reverse Linked List  (0) 2026.01.22
LeetCode 328. Odd Even Linked List  (0) 2026.01.21
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode 1448. Count Good Nodes in Binary Tree
  • LeetCode 104. Maximum Depth of Binary Tree
  • LeetCode 2130. Maximum Twin Sum of a Linked List
  • LeetCode 206. Reverse Linked List
코드 유랑자 승열
코드 유랑자 승열
코드 유랑자 승열의 프로그래밍 일지를 남기는 공간입니다.
  • 코드 유랑자 승열
    승열의 프로그래밍 시네마
    코드 유랑자 승열
  • 전체
    오늘
    어제
  • 링크

    • 깃허브 보러가기
    • 링크드인 보러가기
    • 카테고리
      • 코딩테스트
        • LeetCode
        • BaekJoon
      • TIL and WIL
        • TIL
        • WIL
      • 주말스터디
      • 내일배움캠프
        • 사전캠프 강의 (SQL)
      • 용어정리
        • Python
        • Python-Library
        • Machine-Learning
        • Deep-Learning
        • AI 활용
        • LLM & RAG
        • Docker
        • Django
        • SQL
        • Java Script
        • etc
      • Daily 코드카타
        • SQL
        • Python 알고리즘
      • 임시저장
      • 보류
  • 태그

    langchain
    RAG
    오블완
    llm
    django
    word2vec
    티스토리챌린지
    vector db
    template
    View
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
코드 유랑자 승열
LeetCode 872. Leaf-Similar Trees
상단으로

티스토리툴바