/** * 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 maxDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return 0; int left = maxDepth(root->left) + 1; int right = maxDepth(root->right) + 1; if (left > right) return left; else return right; } };Balanced Binary Tree
----------------------------------------
Efficiency: O(n^2), is there a better way to do this?
/** * 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 depth(TreeNode *root) { if (root == NULL) return 0; int left = depth(root->left) + 1; int right = depth(root->right) + 1; if (left > right) return left; else return right; } bool isBalanced(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return true; return isBalanced(root->left) && isBalanced(root->right) && abs(depth(root->left) - depth(root->right)) < 2; } };Update on Jan-18-2015
O(n), each node is only visited once
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool flag; int getHeight(TreeNode *root) { if (root == NULL) { return 0; } int leftH = getHeight(root->left) + 1; int rightH = getHeight(root->right) + 1; if (abs(leftH - rightH) > 1) flag = false; return max(leftH,rightH); } bool isBalanced(TreeNode *root) { flag = true; getHeight(root); return flag; } };
Update on Feb-07-2019, in Java
Get the height of each node
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isBalanced(TreeNode root) { return dfs(root) != -1; } private int dfs(TreeNode root) { if (root == null) return 0; int left = dfs(root.left); int right = dfs(root.right); if (left == -1 || right == -1) return -1; if (Math.abs(left - right) > 1) return -1; return Math.max(left, right) + 1; } }
No comments:
Post a Comment