您的位置:首页 > Web前端 > Node.js

翻转二叉树(深搜-先序遍历-交换Node)

2015-10-27 17:38 501 查看
题目:翻转二叉树,例如

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

to

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


已知二叉树的节点定义如下:

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}


分析:该题有个小故事:Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

该题可以使用深搜中的先序遍历的思路,依次交换左右TreeNode,注意是交换TreeNode,而不是交换TreeNode的值。下面是翻转的过程:

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


AC代码如下:

public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;

invertTree(root.left);
invertTree(root.right);
return root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: