[leetcode] 110. Balanced Binary Tree
2016-07-19 03:56
281 查看
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.
解法一:
添加一个recursive函数getDepth(Node*),获取当前node的depth。并将此函数用到isBlanced中,并recursive的检查tree中的每一个node。该方法时间复杂度为O(nlogn)。
解法二:
该解法不需要遍历所有节点。只要发现子tree不是balance,返回-1,表示tree不是balanced。不然则返回子tree的真实深度。
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.
解法一:
添加一个recursive函数getDepth(Node*),获取当前node的depth。并将此函数用到isBlanced中,并recursive的检查tree中的每一个node。该方法时间复杂度为O(nlogn)。
/** * 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: bool isBalanced(TreeNode* root) { if(!root) return true; if (abs(getDepth(root->left)-getDepth(root->right)) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } int getDepth(TreeNode* root){ if (!root) return 0; return 1+max(getDepth(root->left),getDepth(root->right)); } };
解法二:
该解法不需要遍历所有节点。只要发现子tree不是balance,返回-1,表示tree不是balanced。不然则返回子tree的真实深度。
/** * 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: 4000 bool isBalanced(TreeNode* root) { if (!root) return true; if (checkDepth(root) == -1) return false; else return true; } int checkDepth(TreeNode* root){ if (!root) return 0; int left = checkDepth(root->left); if (left == -1) return -1; int right = checkDepth(root->right); if (right == -1) return -1; int diff = abs(left-right); if (diff > 1) return -1; return 1+max(left,right); } };
相关文章推荐
- RM格式压缩电影软件 Easy RealMedia Producer Full V1.94 下载
- 在IE 浏览器中使用 jquery的fadeIn() 效果 英文字符字体加粗
- 比较简单的jquery教程 Easy Ajax with jQuery 中文版全集第1/3页
- Easy RM RMVB to DVD Burner v1.3.8 汉化版 下载 附注册码
- Expandable "Detail" Table Rows
- linux下安装easy_install的方法
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- python在Windows下安装setuptools(easy_install工具)步骤详解
- 归纳整理文件Easy Duplicate Finder2.24 破解版
- DM*** and Easy *** Server with ISAKMP Profiles
- easy ***
- cisco packet tracer 5.3 实现基于3A的easy ***
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart