leetcode hot 100 刷题笔记

226. 翻转二叉树

前序遍历即可,每层递归交换左右子节点

leetcode hot 100 刷题笔记
 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 class Solution {
11     public TreeNode invertTree(TreeNode root) {
12         // 前序遍历反转即可
13         preorder(root);
14         return root;
15     }
16 
17     public void preorder(TreeNode node) {
18         if(node==null){
19             return;
20         }
21         TreeNode left = node.left;
22         node.left = node.right;
23         node.right = left;
24         preorder(node.left);
25         preorder(node.right);
26     }
27 }
View Code

时间复杂度O(n),空间复杂度O(1).

上一篇:【剑指Offer-07】重建二叉树


下一篇:589. N叉树的前序遍历