二叉树
树(Tree)是n(n>=0)个结点的有限集。n=0时称为空树。在任意一棵非空树中:(1)有且仅有一个特定的称为根(Root)的结点;(2)当n>1时,其余结点可分为m(m>0)个互不相交的有限集Ti、T2、······、Tm,其中每一个集合本身又是一棵树,并且称为根的子树(SubTree)。
1.二叉树的代码实现
- Java代码实现
/**
* 二叉树的实现
*/
public class TreeNode {
//二叉树的属性
public int value;//二叉树的值
public TreeNode left;//二叉树的左孩子
public TreeNode right;//二叉树的右孩子
public TreeNode(int value) {
this.value = value;
}
public TreeNode(int value, TreeNode left, TreeNode right) {
this.value = value;
this.left = left;
this.right = right;
}
@Override
public String toString(){
return String.valueOf(this.value);
}
}
- C代码实现
typedef struct TreeNode{
int value;//值
TreeNode* left;//左孩子
TreeNode* right;//右孩子
}TreeNode;
2.二叉树的初始化
- Java代码实现
public static void main(String[] args) {
/* 树的初始化
1
/\
2 3
/ /\
4 5 6
*/
TreeNode root = new TreeNode(1,
new TreeNode(2, new TreeNode(4), null),
new TreeNode(3, new TreeNode(5), new TreeNode(6)));
}
- C语言代码实现
int main(){
/* 树的初始化
1
/\
2 3
/ /\
4 5 6
*/
TreeNode* root;
root->value = 1;
root->left = (TreeNode*) malloc(sizeof(TreeNode));
root->right = (TreeNode*) malloc(sizeof(TreeNode));
TreeNode* left1 = root->left;
left1->value = 2;
left1->left = (TreeNode*) malloc(sizeof(TreeNode));
left1->right = NULL;
TreeNode* left2 = left1->left;
left2->value = 4;
left2->left = NULL;
left2->right = NULL;
TreeNode* right1 = root->right;
right1->value = 3;
right1->left = (TreeNode*) malloc(sizeof(TreeNode));
TreeNode* left3 = right1->left;
left3->value = 5;
left3->left = NULL;
left3->right = NULL;
right1->right = (TreeNode*) malloc(sizeof(TreeNode));
TreeNode* right3 = right1->right;
right3->value = 6;
right3->left = NULL;
right3->right = NULL;
}
简化上述代码
int main(){
/* 树的初始化
1
/\
2 3
/ /\
4 5 6
*/
TreeNode* root = initNode(1);
root->left = initNode(2);
root->right = initNode(3);
root->left->left = initNode(4);
root->right->left = initNode(5);
root->right->right = initNode(6);
proOlder(root);
}
/*树的初始化*/
TreeNode* initNode(int value){
TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode));
node->value = value;
node->left = NULL;
node->right = NULL;
return node;
}