Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to flip binary Tree in LeetCode

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to flip the binary tree in LeetCode, which is very detailed and has a certain reference value. Interested friends must read it!

Topic description:

Flip a binary tree.

Example:

Enter:

Output:

Analysis of ideas:

Through observation, we find that as long as the left and right child nodes of each node on the binary tree are exchanged, the final result is the binary tree completely flipped.

This topic is relatively simple, the key idea is that we find that flipping the whole tree is to swap the left and right child nodes of each node, so we put the code of swapping the left and right child nodes in the preorder traversal position.

It is worth mentioning that it is also possible to exchange the code of the left and right child nodes in the post-order traversal position, but not in the middle-order traversal position.

Java implementation / * *

* Definition for a binary tree node.

* public class TreeNode {

* int val

* TreeNode left

* TreeNode right

* TreeNode () {}

* TreeNode (int val) {this.val = val;}

* TreeNode (int val, TreeNode left, TreeNode right) {

* this.val = val

* this.left = left

* this.right = right

*}

*}

, /

Class Solution {

Public TreeNode invertTree (TreeNode root) {

If (root==null) {

Return root

}

TreeNode tmp=root.left

Root.left=root.right

Root.right=tmp

InvertTree (root.left)

InvertTree (root.right)

Return root

}

}

Python implements class Solution:

Def invertTree (self, root: TreeNode)-> TreeNode:

If not root:

Return root

Left = self.invertTree (root.left)

Right = self.invertTree (root.right)

Root.left, root.right = right, left

Return root

The above is all the contents of the article "how to flip a binary tree in LeetCode". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report