144. Binary Tree Preorder Traversal
问题
Given the root of a binary tree, return the preorder traversal of its nodes’ values.
先序遍历。
先将当前节点加入数组。
然后递归左子节点。
最后递归右子节点。
1 | /** |
144. Binary Tree Preorder Traversal
问题
Given the root of a binary tree, return the preorder traversal of its nodes’ values.
先序遍历。
先将当前节点加入数组。
然后递归左子节点。
最后递归右子节点。
1 | /** |
116. Populating Next Right Pointers in Each Node
问题
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
1
2
3
4
5
6 struct Node {
int val;
Node *left;
Node *right;
Node *next;
>}Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
递归,当root为null时返回。
如果root有右节点,则左节点next指向右节点。
如果root有右节点同时next已经指向了一个节点,则将其右节点next指向该节点的左子节点。
递归左右子节点,并返回root。
1 | /* |
BFS搜索每一个节点,将节点指向队列中next下一个节点。
当计数器达到2的指数时,将节点指向null。
1 | class Solution { |
问题
You are given two binary trees root1 and root2.Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return the merged tree.
Note: The merging process must start from the root nodes of both trees.
递归。将root1和root2合并到root1。
如果一个节点为null,则返回另一个节点。
否则root1的值为root1 + root2的值。
root1.left递归root1和root2的left。
root2.right递归root1和root2的right。
返回root1。
1 | /** |
答案
An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with newColor.
Return the modified image after performing the flood fill.
深度优先搜索。
如果当前像素颜色等于最初的颜色,则变更为新颜色。
然后继续递归四个周围的像素。
1 | class Solution { |