您的位置:首页 > 其它

翻转二叉树(Invert Binary Tree)

2015-07-08 12:54 274 查看
最近翻转二叉树算法成为了热点算法,起因就是因为homebrew的作者去google面试的事件,然后业界又出现了一场撕逼大战:对于工作经验和算法能力哪个更重要?不想把战火进一步蔓延,所以在这我也不发表观点了,直接进入正题。

问题描述(直接copy自LeetCode):

Invert a binary tree.
4
/   \
2     7
/ \   / \
1   3 6   9

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

这个算法其实不难,在LeetCode中的难易评级也是easy,算法的核心就是递归思想,下面直接上代码,也是笔者在LeetCode中的答案,因为LeetCode不支持oc,只能用js了

/**
* Definition for a binary tree node.
* function TreeNode(val) {
*     this.val = val;
*     this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if(root === null){
return null;
}
root.left = invertTree(root.left);
root.right = invertTree(root.right);

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