题目链接:点击打开链接
题目大意:略
解题思路:略
相关企业
- 字节跳动
- 谷歌(Google)
- 苹果(Apple)
- 亚马逊(Amazon)
- 微软(Microsoft)
- 美团
- 猿辅导
- SAP 思爱普
- 阿里巴巴
- 抖音
AC 代码
- Java
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/// 解决方案(1)classSolution { booleanres=true; publicbooleanisBalanced(TreeNoderoot) { dfs(root); returnres; } intdfs(TreeNodenode) { if (node==null) { return0; } intl=dfs(node.left) +1; intr=dfs(node.right) +1; if (Math.abs(l-r) >1) { res=false; } returnMath.max(l, r); } } // 解决方案(2)classSolution { publicbooleanisBalanced(TreeNoderoot) { returnrecur(root) !=-1; } privateintrecur(TreeNoderoot) { if (root==null) return0; intleft=recur(root.left); if(left==-1) return-1; intright=recur(root.right); if(right==-1) return-1; returnMath.abs(left-right) <2?Math.max(left, right) +1 : -1; } } // 解决方案(3)classSolution { publicbooleanisBalanced(TreeNoderoot) { if (root==null) returntrue; returnMath.abs(depth(root.left) -depth(root.right)) <=1&&isBalanced(root.left) &&isBalanced(root.right); } privateintdepth(TreeNoderoot) { if (root==null) return0; returnMath.max(depth(root.left), depth(root.right)) +1; } }
- C++
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/// 解决方案(1)classSolution { public: boolisBalanced(TreeNode*root) { returnrecur(root) !=-1; } private: intrecur(TreeNode*root) { if (root==nullptr) return0; intleft=recur(root->left); if(left==-1) return-1; intright=recur(root->right); if(right==-1) return-1; returnabs(left-right) <2?max(left, right) +1 : -1; } }; // 解决方案(2)classSolution { public: boolisBalanced(TreeNode*root) { if (root==nullptr) returntrue; returnabs(depth(root->left) -depth(root->right)) <=1&&isBalanced(root->left) &&isBalanced(root->right); } private: intdepth(TreeNode*root) { if (root==nullptr) return0; returnmax(depth(root->left), depth(root->right)) +1; } };