Table of contents
You are given the root node of a binary tree
root
, flip the binary tree and return its root node.Example 1:
Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]Example 2:
Input: root = [2,1,3] Output: [2,3,1]Example 3:
Input: root = [] Output: []hint:
- The number of nodes in the tree
[0, 100]
is within-100 <= Node.val <= 100
Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { // 从上到下左右子树的位置跟输入正好是相反的,递归交换 public TreeNode invertTree(TreeNode root) { // 终止条件:当前节点为 null 时返回 if(root==null) return null; // 交换当前节点的左右节点 TreeNode tmp=root.right; root.right=root.left; root.left=tmp; // 递归的交换当前节点的左节点,右节点 invertTree(root.left); invertTree(root.right); return root; } }
operation result: