Minimum depth of Binary Tree
OJ: https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
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.
Idea: traverse in sequence. Note: when there is only one child node, the depth is the child node depth plus 1.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int minDepth(TreeNode *root) { if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return 1; int l = minDepth(root->left); int r = minDepth(root->right); return (l && r) ? min(l, r) + 1 : (l+r+1); }};
Balanced Binary Tree
OJ: https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
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 SubtreesEveryNode never differ by more than 1.
Idea: traverse in sequence. Both the left and right subtree judgment results and the left and right subtree depth must be returned for further judgment.
Therefore, either a pair <bool, int> is returned, or a reference is added to the function parameter to pass the return value.
Method 1: return a pair <bool, int>: (more concise)
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */typedef pair<bool, int> Pair;Pair judge(TreeNode *root) { if(root == NULL) return Pair(true, 0); Pair L = judge(root->left); Pair R = judge(root->right); return Pair(L.first && R.first && abs(L.second-R.second) < 2, max(L.second, R.second)+1);}class Solution {public: bool isBalanced(TreeNode *root) { return judge(root).first; }};
Method 2: Add a reference
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */bool judge(TreeNode *root, int& depth) { if(root == NULL) { depth = 0; return true; } int l, r; if(judge(root->left, l) && judge(root->right, r)) { depth = 1 + max(l, r); if(l-r <= 1 && l-r >= -1) return true; else return false; }}class Solution {public: bool isBalanced(TreeNode *root) { int depth; return judge(root, depth); }};
Maximum depth of Binary Tree
OJ: https://oj.leetcode.com/problems/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.
Note: This question is omitted.
class Solution {public: int maxDepth(TreeNode *root) { return root ? max(maxDepth(root->left), maxDepth(root->right))+1 : 0; }};
33. Minimum depth of Binary Tree & balanced binary tree