标签:style class blog code http tar
题目:Balanced 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 subtrees of every node never differ by more than 1.
个人思路:
1、判断每个节点(子树)的高度差,高度差在绝对值为1的范围内便是平衡二叉树
2、可以适当改造计算树高度的方法,即树的高度为左子树与右子树高度较大者加1
代码:
1 #include <stddef.h> 2 #include <iostream> 3 /** 4 * Definition for binary tree 5 * struct TreeNode { 6 * int val; 7 * TreeNode *left; 8 * TreeNode *right; 9 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 * }; 11 */ 12 13 struct TreeNode 14 { 15 int val; 16 TreeNode *left; 17 TreeNode *right; 18 TreeNode(int x) : val(x), left(NULL), right(NULL) {} 19 }; 20 21 class Solution 22 { 23 public: 24 bool isBalanced(TreeNode *root) 25 { 26 balanced = true; 27 getDepth(root); 28 29 return balanced; 30 } 31 int getDepth(TreeNode *root) 32 { 33 if (root == NULL) 34 { 35 return 0; 36 } 37 38 int leftDepth = getDepth(root->left); 39 int rightDepth = getDepth(root->right); 40 41 if (leftDepth - rightDepth > 1 || leftDepth - rightDepth < -1) 42 { 43 balanced = false; 44 } 45 46 return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; 47 } 48 private: 49 bool balanced; 50 }; 51 52 int main() 53 { 54 TreeNode *root = new TreeNode(1); 55 root->right = new TreeNode(1); 56 root->right->right = new TreeNode(1); 57 Solution s; 58 s.isBalanced(root); 59 std::cout << root->val << std::endl << root->right->val << std::endl << root->right->val << std::endl; 60 system("pause"); 61 62 return 0; 63 }
上网搜了一些帖子,方法都是类似,就不贴出来了
leetcode - Balanced Binary Tree,布布扣,bubuko.com
leetcode - Balanced Binary Tree
标签:style class blog code http tar
原文地址:http://www.cnblogs.com/laihaiteng/p/3795408.html