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