Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to flip binary Tree in LeetCode

Shulou Source: shulou.com Published: 2022-06-01 17:59:41 09月21日 Update

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!

Tags: Node location code content that is ideas articles topics no worth mentioning value key interests guys partners more knowledge examples results industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Docker Shulou Tech Info Huawei Shulou Technology