Binary Tree(1)

Tree Node

Binary Tree Representation in C: A tree is represented by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL.
A Tree node contains following parts.

  • Data
  • Pointer to left child
  • Pointer to right child
struct TreeNode
{
    DataType data;
    struct TreeNode * leftchild;
    struct TreeNode * rightchild;
};

Create a simple tree with 4 nodes in C

typedef struct node
{
     DataType data;//data domain
     struct node *left; //left child
    struct node * right;  // right child
} Node;

// new Tree Node
Node *  newNode(DataType data)
{
     Node * node = (Node*)malloc(sizeof(Node));
     node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

int main(void)
{
 Node * root  = newNode(1);
 root->left  = newNode(2);
 root->right = newNode(3);
root->left->left = newNode(4);
getchar();
return 0;
}

Created using Python

class Node:
    def __init__(self,key):
        self.left = None
        self.right = None
        self.val = key

root = Node(1)
root.left  = Node(2)
root.right = Node(3)
root.left.left = Node(4)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容