leetcode笔记:Invert Binary Tree
程序员文章站
2022-05-28 19:59:16
一. 题目描述
invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4...
一. 题目描述
invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9
to
4 / \ 7 2 / \ / \ 9 6 3 1
trivia:
this problem was inspired by this original tweet by max howell:
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.
二. 题目分析
题目意图很明显,即翻转一棵二叉树。后面是几句话,大概的意思是:
google:我们有90%的工程师在使用你写的软件(homebrew?),但你居然不会在白板上翻转一棵二叉树,真是操蛋。
这是一道任何程序员都应该会的题,递归或者队列迭代解法都可以实现,不多加赘述。
三. 示例代码
// c++,递归 /** * definition for a binary tree node. * struct treenode { * int val; * treenode *left; * treenode *right; * treenode(int x) : val(x), left(null), right(null) {} * }; */ class solution { public: treenode* inverttree(treenode* root) { if (root == null) return root; treenode* temp = root->left; root->left = root->right; root->right = temp; inverttree(root->left); inverttree(root->right); return root; } };
# python,递归 # definition for a binary tree node. # class treenode: # def __init__(self, x): # self.val = x # self.left = none # self.right = none class solution(object): def inverttree(self, root): """ :type root: treenode :rtype: treenode """ if root is none: return none root.left, root.right = root.right, root.left self.inverttree(root.left) self.inverttree(root.right) return root
四. 小结
该题意在帮助我们复习数据结构的基础。
上一篇: 普陀山有什么好推荐?
下一篇: Servlet与JSP教程
推荐阅读
-
leetcode笔记:Invert Binary Tree
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
LeetCode 235--二叉搜索树的最近公共祖先 ( Lowest Common Ancestor of a Binary Search Tree ) ( C语言版 )
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树
-
[Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
-
leetcode 235. Lowest Common Ancestor of a Binary Search Tree(二叉树的最低共同祖先)
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree