LeetCode 226 Invert Binary Tree

题意

给予一颗二叉树,返回其每层节点的平均值.

例 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
给予树:

4
/ \
2 7
/ \ / \
1 3 6 9

返回:

4
/ \
7 2
/ \ / \
9 6 3 1

解法

采用深度优先遍历, 从最底层节点开始, 将每个节点的左右节点进行交换即可.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return root;
}

TreeNode left = root.left;
TreeNode right = root.right;
if (left != null) {
invertTree(left);
}
if (right != null) {
invertTree(right);
}

root.left = right;
root.right = left;

return root;
}
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Invert Binary Tree.
Memory Usage: 33.5 MB, less than 98.89% of Java online submissions for Invert Binary Tree.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-226/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!