LeetCode: Balanced Binary Tree

C++版

 1 /**

 2  * Definition for binary tree

 3  * struct TreeNode {

 4  *     int val;

 5  *     TreeNode *left;

 6  *     TreeNode *right;

 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 8  * };

 9  */

10 class Solution {

11 public:

12     int dfs(TreeNode *root, bool &flag, int cur) {

13         if (!root || !flag) return cur;

14         int leftH = dfs(root->left, flag, cur+1);

15         if (!flag) return cur;

16         int rightH = dfs(root->right, flag, cur+1);

17         if (abs(leftH-rightH) <= 1 && flag) flag = true;

18         else flag = false;

19         return max(leftH, rightH);

20     }

21     bool isBalanced(TreeNode *root) {

22         // Start typing your C/C++ solution below

23         // DO NOT write int main() function

24         if (!root) return true;

25         bool flag = true;

26         if (abs(dfs(root->left, flag, 0)-dfs(root->right, flag, 0)) <= 1 && flag) return true;

27         else return false;

28     }

29 };

 C#版,注意ref的用法,用ref的时候不需要再函数内对参数进行赋值,另外调用的时候都要写上ref。另外该函数必须是static

 1 /**

 2  * Definition for a binary tree node.

 3  * public class TreeNode {

 4  *     public int val;

 5  *     public TreeNode left;

 6  *     public TreeNode right;

 7  *     public TreeNode(int x) { val = x; }

 8  * }

 9  */

10 public class Solution {

11     static public int depth(TreeNode root, ref bool flag, int curDepth)

12     {

13         if (root == null || !flag) return curDepth;

14         int leftDepth = depth(root.left, ref flag, curDepth + 1);

15         if (!flag) return curDepth;

16         int rightDepth = depth(root.right, ref flag, curDepth + 1);

17         if (Math.Abs(leftDepth - rightDepth) <= 1 && flag) flag = true;

18         else flag = false;

19         return Math.Max(leftDepth, rightDepth);

20     }

21     public bool IsBalanced(TreeNode root) {

22         if (root == null) return true;

23         bool flag = true;

24         return Math.Abs(depth(root.left, ref flag, 0)-depth(root.right, ref flag, 0)) <= 1 && flag;

25     }

26 }
View Code

 

你可能感兴趣的:(LeetCode)