[Leetcode] 226. Invert Binary Tree JAVA

Source: Internet
Author: User

Topic:

Invert a binary tree.

     4   /     2     7/\   /1   3 6   9

To

     4   /     7     2/\   /9   6 3   1

test instructions and analysis: a binary tree is given, and the left and right sub-trees are exchanged on each node. For a node that needs to be exchanged, there are three cases: (1) There are left dial hand tree, no right subtree, (2) There is right subtree, no left subtree, (3) There are all sub-trees; in three cases, the left and right sub-trees are exchanged, and then the subtree can be recursive to get the result.

Code:

/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode inverttree (TreeNode root) {if(root==NULL)return NULL;        Exchange (root); returnRoot; }     Public voidExchange (TreeNode node) {if(node.left==NULL&&node.right==NULL)            return; Else{            if(node.left==NULL&&node.right!=NULL) {Node.left=Node.right; Node.right=NULL;                Exchange (Node.left); return; }Else if(node.right==NULL&&node.left!=NULL) {Node.right=Node.left; Node.left=NULL;            Exchange (Node.right); }Else{TreeNode temp=Node.left; Node.left=Node.right; Node.right=temp;                Exchange (Node.left);            Exchange (Node.right); }        }    }}

[Leetcode] 226. Invert Binary Tree JAVA

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.