145. Binary Tree Postorder Traversal
问题
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
后序遍历。
先递归左子节点。
然后递归右子节点。
最后将当前节点加入数组。
1 | /** |
145. Binary Tree Postorder Traversal
问题
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
后序遍历。
先递归左子节点。
然后递归右子节点。
最后将当前节点加入数组。
1 | /** |
94. Binary Tree Inorder Traversal
问题
Given the root of a binary tree, return the inorder 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 | /** |