本文涉及 LeetCode
226. 翻转二叉树,难度 Easy
114. 将二叉树展开为链表,难度 Medium
116. 填充二叉树节点的右侧指针,难度 Medium
226、翻转二叉树,难度 Easy
Invert a binary tree.
Trivia:Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
This problem was inspired by this original tweet by Max Howell:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
//将整棵树的节点翻转
class Solution {
public TreeNode invertTree(TreeNode root) {
//base case 基本情况
if (root == null){
return null;
}
/**** 前序遍历位置 ****/
// root 节点需要交换它的左右子节点
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
// 让左右子节点继续翻转它们的子节点
invertTree(root.left);
invertTree(root.right);
return root;
}
}
116. 填充二叉树节点的右侧指针,难度 Medium
114. 将二叉树展开为链表,难度 Medium
Given a binary tree, flatten it to a linked list in-place.