序
本文次要记录一下leetcode树之从翻转二叉树
题目
翻转一棵二叉树。
示例:
输出:
4
/ \
2 7
/ \ / \
1 3 6 9
输入:
4
/ \
7 2
/ \ / \
9 6 3 1
备注:
这个问题是受到 Max Howell 的 原问题 启发的 :
谷歌:咱们90%的工程师应用您编写的软件(Homebrew),然而您却无奈在面试时在白板上写出翻转二叉树这道题,这太蹩脚了。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
题解
/**
* 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 tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);
return root;
}
}
小结
这里采纳递归的思路,首先用tmp保留一下left节点,之后递归翻转right节点赋值给left,再递归翻转tmp赋值为right。
doc
- 翻转二叉树
发表回复