[LeetCode-interview algorithm classic-Java implementation] [226-Invert Binary Tree (reverse Binary Tree)], leetcode -- java

Source: Internet
Author: User

[LeetCode-interview algorithm classic-Java implementation] [226-Invert Binary Tree (reverse Binary Tree)], leetcode -- java
[226-Invert Binary Tree (reverse Binary Tree )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Download the Code [https://github.com/wang-jun-chao]Original question

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9

To

     4   /   \  7     2 / \   / \9   6 3   1

Theme

Flip a binary tree.

Solutions

Exchange left and right subtree of each node, and perform the same operation on its left and right subnodes.

Code Implementation

Tree node class

public class TreeNode {    int val;    TreeNode left;    TreeNode right;    TreeNode(int x) { val = x; }}

Algorithm Implementation class

public class Solution {      public TreeNode invertTree(TreeNode root) {        if (root != null) {            invertTreeNode(root);        }        return root;    }    public void invertTreeNode(TreeNode root) {        if (root != null) {            TreeNode tmp = root.left;            root.left = root.right;            root.right = tmp;            invertTree(root.left);            invertTree(root.right);        }    }}
Evaluation Result

  Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.

Note Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/48100759]

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.