Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 简单题,不过注意叶子结点是两个子树都是NULL的指针.只有一个子树NULL的不是. struct TreeNode { int val; TreeNode *left; TreeN…
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…
Description Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example Given binary tr…
题目: 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. 代码:…
1.直接把递归把左右子树翻转即可 AC代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void invert(TreeNode* root) {…
Check if two binary trees are identical. Identical means the two binary trees have the same structure and every identical position has the same value. Have you met this question in a real interview?     Example 1 1 / \ / \ 2 2 and 2 2 / / 4 4 are ide…
Check if two binary trees are identical. Identical means the two binary trees have the same structure and every identical position has the same value. Example 1 1 / \ / \ 2 2 and 2 2 / / 4 4 are identical. 1 1 / \ / \ 2 3 and 2 3 / \ 4 4 are not iden…
C++ /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @aaram a, b, the root of bin…
原题 寻找二叉树最短深度 这里用了dfs,beat 100%,4ms class Solution { public: int minDepth(TreeNode *root, int minNum = 0) { if (root == NULL) { return minNum == 0 ? minNum : 999999; } if (root->left == NULL && root->right == NULL) return minNum + 1; return m…
原题 思路: 题目其实就是求左右最长深度的和 class Solution { private: int res = 0; public: int diameterOfBinaryTree(TreeNode *root) { dfs(root); return res; } int dfs(TreeNode *root) { if (root == NULL) { return 0; } int leftNum = dfs(root->left); int rightNum = dfs(root…