二叉树的最近父结点的查找(Least Common Ancestor)

来源:互联网 发布:淘宝大图轮播尺寸 编辑:程序博客网 时间:2024/06/06 02:01

二叉树最近父结点的查找分为3种情况:结点中带有parent指针;结点中只有左右孩子的指针;树是一颗二叉查找树


1.  结点带有parent指针的二叉树。思想是先从给定的两个结点a 和 b出发,回溯到root,分别记录步长,然后同步使步长相等,之后同步往root回溯,第一个相等的结点就是最近父节点。

struct Node{struct Node *parent, *left, *right;int value;};struct Node* FindLeastCommonAncestor(struct Node* root, struct Node* a, struct Node* b){int step_a = 0;int step_b = 0;struct Node* temp = a;while(temp->parent != root){step_a++;temp = temp->parent;}temp = b;while(temp->parent != root){step_b++;temp = temp->parent;}struct Node* path_l = step_a > step_b? a : b;struct Node* path_s = step_a > step_b? b : a;int step = abs(step_a - step_b);while(step > 0){path_l = path_l->parent;step--;}while(path_l != path_s){path_l = path_l->parent;path_s = path-s-.parent;}return path_l;}


2.二叉树是一颗二叉查找树。思想是,找到一个结点,是这个结点的值在所找的两个结点的值之间


struct Node{struct Node *left, *right;int value;};struct Node* FindLeastCommonAncestor(struct Node* root, int a, int b){int max_value = a > b? a : b;int min_value = a > b? b : a;struct Node *path = root;while(path){if(path->value < max && path->value min || path->value == min || path->value == max )return path;else if(path->value < min)path = path->left;elsepath = path->right;}}


3.二叉树是一颗普通的二叉树。用递归的思想,分三种情况:root为NULL; a 或 b 等于根结点;最近父结点在根的左子树或根的右子树


struct Node{struct Node *left, *right;int value;};struct Node* FindLeastCommonAncestor(struct Node* root, struct Node* a, struct Node* b){if(root == NULL) return NULL;if(root == a || root == b ) return root;struct Node* pl = FindLeastCommonAncestor(root->left, a, b);struct Node* pr = FindLeastCommonAncestor(root->right, a, b);if(pl && pr) return root;return pl? pl : pr;}


0 0