江南無所謂 聊贈一枝春node
知足條件: 左節點值 < 根節點值 < 右節點值git
typedef struct TreeNode { int data; struct TreeNode *left; struct TreeNode *right; } TreeNode;
typedef struct tree { struct TreeNode *root; } Tree;
插入節點github
void insertNode (Tree *tree, int value) { TreeNode *node1 = malloc(sizeof(TreeNode)); node1->data = value; node1->left = NULL; node1->right = NULL; if(tree->root == NULL){ tree->root = node1; } else { TreeNode *temp = tree->root; while (temp != NULL) { if(value < temp->data){ if(temp->left == NULL) { temp->left = node1; return ; } else { temp = temp->left; } } else { if(temp->right == NULL) { temp->right = node1; return; } else { temp = temp->right; } } } } }
// 前序遍歷 根->左->右 void preorderTraverse(TreeNode *tree) { if(tree == NULL) {return;} NSLog(@"%d ", tree->data); preorderTraverse(tree->left); preorderTraverse(tree->right); } //中序遍歷 左->根->右 void midTraverse(TreeNode *tree) { if(tree == NULL) {return;} midTraverse(tree->left); NSLog(@"%d ", tree->data); midTraverse(tree->right); } //後序遍歷 左->右->根 void postorderTraversal(TreeNode *tree) { if(tree == NULL) {return;} postorderTraversal(tree->left); postorderTraversal(tree->right); NSLog(@"%d ", tree->data); }
int getBSTHeight (TreeNode *node) { if (node == NULL) { return 0; } else { int leftH = getBSTHeight(node->left); int rightH = getBSTHeight(node->right); int max = leftH; if (max < rightH) { max = rightH; } return max+1; } }
int getMaxNum(TreeNode *node) { if (node == NULL) { return -1; } else { int leftMax = getMaxNum(node->left); int rightMax = getMaxNum(node->right); int current = node->data; int max = leftMax; if (rightMax > max) { max = rightMax; } if (current>max) { max = current; } return max; } }
int arr[] = {6,3,8,2,5,1,7}; // 建立樹 Tree *tree = malloc(sizeof(Tree)); tree->root = NULL; for(int i=0; i<7; i++) { // 樹中插入節點 insertNode(tree, arr[i]); } // 計算樹的高度 int treeH = getBSTHeight(tree->root); NSLog(@"%d\n", treeH); // 計算樹的最大值 int maxNum = getMaxNum(tree->root); NSLog(@"%d\n", maxNum);
BST樹中序遍歷的獲得的是一個有序的數列
post
連接描述測試