Invert a binary tree.
4 / 2 7 / \ / 1 3 6 9
to
4 / 7 2 / \ / 9 6 3 1
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode invertTree(TreeNode root) { 12 13 14 if(root!=null) 15 { 16 TreeNode temp = root.left; 17 root.left = root.right; 18 root.right = temp; 19 20 invertTree(root.left); 21 invertTree(root.right); 22 23 return root; 24 } 25 return null; 26 } 27 }
时间: 2024-11-04 14:48:31