avatar

`2015年`文章归档

未分类

二叉树的一些操作

反转二叉树

前一段时间国外某大牛面试Google被刷掉,原因是没有能够徒手写出来反转二叉树的代码,在网上看到了一个人的分析代码,特此记下来。

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

TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
return root;
}
}

阅读剩下更多

默认配图
返回顶部