leetcode#226 Invert Binary Tree

Source: Internet
Author: User

Invert Binary Tree

? Flip Two fork Tree

Here we implement two solutions in Java and Python (two solutions can be implemented entirely in Java or Python:

?

Scenario One: (Java)

/**

? * Definition for a binary tree node.

? * Public class TreeNode {

?* ? ? int Val;

?* ? ? TreeNode left;

?* ? ? TreeNode right;

?* ? ? TreeNode (int x) {val = x;}

?* }

?*/

public class Solution {

? ? Public TreeNode inverttree (TreeNode root) {

? ? ? ? if (root = null)?? return root;

? ? ? ??

? ? ? ? queue<treenode> linenodes = new linkedlist<treenode> ();

? ? ? ? Linenodes.add (root);

? ? ? ??

? ? ? ? TreeNode Current, TMP;

? ? ? ? while (!linenodes.isempty ()) {

? ? ? ? ? ? Current = Linenodes.remove ();

? ? ? ? ? ??

? ? ? ? ? ? TMP = Current.left;

? ? ? ? ? ? Current.left = Current.right;

? ? ? ? ? ? Current.right = tmp;

? ? ? ? ? ??

? ? ? ? ? ? if (current.left! = null) {

? ? ? ? ? ? ? ? Linenodes.add (Current.left);

? ? ? ? ? ? }

? ? ? ? ? ? if (current.right! = null) {

? ? ? ? ? ? ? ? Linenodes.add (Current.right);

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return root;

? ? }

}

Scenario Two: (Python)

# Definition for a binary tree node.

# class TreeNode (object):

# ? ? def __init__ (self, x):

# ? ? ? ? Self.val = X

# ? ? ? ? Self.left = None

# ? ? ? ? Self.right = None

?

Class solution (Object):

? ? def inverttree (self, root):

? ? ? ? """

? ? ? ? : Type Root:treenode

? ? ? ? : Rtype:treenode

? ? ? ? """

? ? ? ? If Root==none:

? ? ? ? ? ? return root

? ? ? ? TMP = Root.left

? ? ? ? Root.left = Self.inverttree (root.right)

? ? ? ? Root.right = Self.inverttree (TMP)

? ? ? ? return root

leetcode#226 Invert Binary Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.