invert binary tree
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. Subscribe to see which companies asked this question
问题分析很简单,其实就是一个深度优先遍历的问题,它的一个子问题就是左孩子和右孩子已经完成交换,然后把左孩子和右孩子交换就好。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
if (root == NULL)
return ;
invertTree(root->left);
invertTree(root->right);
struct TreeNode *p = root->left;
root->left = root->right;
root->right = p;
}
Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from
the root node down to the farthest leaf node.Subscribe to see which companies asked this question
找出一个树的最大深度。也是一个递归的问题,首先如果知道左子树和右子树的深度,那么在选取一个最大的然后加一就行。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
if (root == NULL) return 0;
int dLeft = maxDepth(root->left);
int dRight = maxDepth(root->right);
return dLeft > dRight ? dLeft+1 : dRight+1;
}
Move Zeroes
Given an array nums, write a function to move all 0’s to the end of it
while maintaining the relative order of the non-zero elements.For example, given nums = [0, 1, 0, 3, 12], after calling your
function, nums should be [1, 3, 12, 0, 0].Note: You must do this in-place without making a copy of the array.
Minimize the total number of operations.
找出所有的0,然后把所有的0放到最后,但是原来非0的数字顺序不能改变。
思路就是
改进的冒泡排序的方式,形象的方式就是当0与0相碰的时候,两个0合并成一个大”0“,这个大”0“通过记录这个大”0“的前面的位置和size表示,如果碰到的不是0的时候,就把这个数字放在大”0“后面,也就是大”0“向前前进一步。
void moveZeroes(int* nums, int numsSize) {
int i, j;
j = 0;
int k = 0;
int tmp;
while (nums[k++] != 0);
i = k-1;
j = 1;
for (; k < numsSize; k++)
if (nums[k] != 0) {tmp = nums[k]; nums[k]= nums[i-j+1]; nums[i-j+1] = tmp; i=i+1;}
else{j++; i++;}
}