Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does LeetCode solve the same tree problem

Shulou Source: shulou.com Published: 2022-06-01 13:37:22 11月01日 Update

Editor to share with you LeetCode how to solve the same tree problem, I believe that most people do not know much, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

1. Title

one hundred。 Same tree [1]

two。 Description

Given two binary trees, write a function to verify that they are the same.

If two trees are structurally identical and the nodes have the same value, they are considered to be the same.

Example 1:

Example 2:

Example 3:

3. Train of thought

Using the binary tree to do exercises to recursively traverse the framework, first operate on the root node, and then recursively the left and right child nodes.

Returns true when the current node of both trees is null

Returns false when one of them is null and the other is not null

Returns false when neither is empty but the values are not equal

The operation of the root node is completed in the above three steps, and then the left and right child nodes are recursive.

/ / Recursive access

Void traverse (TreeNode root) {

/ / preorder traversal, manipulating the root node first

Traverse (root.left)

/ / traversal in the middle order, manipulating the left child node

Traverse (root.right)

/ / traversal in post-order, manipulating the right child node

}

4. Implement public boolean isSameTree (TreeNodeTest p, TreeNodeTest Q) {

/ *

* determine the root node first

, /

/ / both are null, which means they are equal.

If (p = = null & & Q = = null) {

Return true

}

/ / one of them is null, which means it is not equal.

If (p = = null | | Q = = null) {

Return false

}

/ / neither of them is null, but the values are different, which means they are not equal.

If (p.val! = q.val) {

Return false

}

/ / after the root node is judged, the left and right nodes are judged

Return isSameTree (p.left, q.left) & & isSameTree (p.right, q.right)

}

The above is all the content of the article "how to solve the same tree problem with LeetCode". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Nodes same recursive two examples articles questions content different next not much function most ideas more framework knowledge structure industry information Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi macOS Shulou Information Microsoft Xiaomi