LeetCode(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.
코드:
class Solution {
public:
   bool DFS(TreeNode* root, int& deep)
  {
    if(root == NULL)
    {
      deep = 0;
      return true;
    }
    int left_deep, right_deep;
    if(DFS(root->left, left_deep) && DFS(root->right, right_deep))
    {
      int diff = abs(left_deep - right_deep);
      if(diff <= 1)
      {
        deep = 1 + (left_deep > right_deep ? left_deep : right_deep);
        return true;
      }
    }
    return false;
  }
  
  bool isBalanced(TreeNode *root) {
    int deep;
    return DFS(root, deep);
  }
};

좋은 웹페이지 즐겨찾기