2012-12-12 29 views

回答

2

它將返回RB樹的黑色高度。如果高度爲0,則該樹是無效的紅黑樹。

int BlackHeight(NodePtr root) 
{ 
    if (root == NULL) 
     return 1; 

    int leftBlackHeight = BlackHeight(root->left); 
    if (leftBlackHeight == 0) 
     return leftBlackHeight; 

    int rightBlackHeight = BlackHeight(root->right); 
    if (rightBlackHeight == 0) 
     return rightBlackHeight; 

    if (leftBlackHeight != rightBlackHeight) 
     return 0; 
    else 
     return leftBlackHeight + root->IsBlack() ? 1 : 0; 
} 
+0

我不明白帶問號和冒號的最後一行的符號...你能澄清嗎? –

+0

這是一個[條件運算符。](http://en.wikipedia.org/wiki/%3F) – healthy

1

下面的代碼驗證是否沿任意路徑的黑色節點的數目是相同

#define RED 0 
#define BLACK 1 

struct rbt { 
    int data; 
    struct rbt *left; 
    struct rbt *right; 
    int parent_color; // parent link color 
    uint64_t nodes_count; // to store number of nodes present including self 
    int level; // to store level of each node 
}; 
typedef struct rbt rbt_t; 

int check_rbt_black_height(rbt_t *root) 
{ 
    if(!root) return 1; 
    else { 
     int left_height = check_black_violation(root->left); 
     int right_height = check_black_violation(root->right); 
     if (left_height && right_height && left_height != right_height) { 
      printf("Error: Black nodes are not same @level=%d\n", root->level); 
      exit(1); 
     } 
     if (left_height && right_height) 
        // do not increment count for red 
      return is_color_red(root) ? left_height : left_height + 1; 
     else 
      return 0; 
    } 
} 

int is_color_red(rbt_t *root) 
{ 
    if(root && root->parent_color == RED) return 1; 
    return 0; 
} 
相關問題