二叉树的最近父结点的查找(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
- 二叉树的最近父结点的查找(Least Common Ancestor)
- 最近共同父结点(LCA,Least Common Ancestor)
- LeetCode 刷题: 两个二叉树节点的最近公共节点Least Common Ancestor
- 二叉树中两个结点的最近公共祖先(Lowest Common Ancestor of a Binary Tree)
- leetcode_235. Lowest Common Ancestor of a Binary Search Tree 查找二叉搜索树最近公共祖先结点
- 第19题 在二叉查找树中找到两个结点的最低公共祖先 Lowest Common Ancestor
- 在二叉树中查找两个节点的最近的公共祖先节点(无回溯指针)(NCA--nearest common ancestor)
- 在二叉树中查找两个节点的最近的公共祖先节点(有回溯指针)(NCA--nearest common ancestor)
- 二叉搜索树(BST)的最近公共祖先(LCA)问题(Lowest Common Ancestor of a Binary Tree)
- 235. Lowest Common Ancestor of a Binary Search Tree (求二叉树中两个节点的最近公共祖先)
- LCA(Least Common Ancestor)
- 设计算法查找二叉树的两个结点最近公共祖先(LCA)
- 两链表的第一个公共结点->二叉树两结点的最近共同父结点
- 235. Lowest Common Ancestor of a Binary Search Tree | 二叉查找树两个节点的最低共同祖先
- LAC(least common Ancestor)算法
- 求二叉树两结点最近的共同祖先结点
- 【Leetcode】查找二叉树中任意结点的最近公共祖先(LCA问题)
- [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点
- Clojure 学习入门(12)—— map/pmap
- 10-排序-03-选择排序
- 文本特征提取方法研究
- NDK开发环境搭建_r8
- 在Windows Azure上基于CentOS 6.3部署MySQL 5.6主从式数据库(1)
- 二叉树的最近父结点的查找(Least Common Ancestor)
- Linux基础.控制台式查看日志
- LeetCode | String to Integer (atoi)
- linux下tar.gz、tar、bz2、zip等解压缩、压缩命令小结
- toj2194Mine(dfs)
- 算法导论 5.1-3
- java提高篇(十四)-----关键字final
- Linux 下压缩与解压.zip和.rar及.7z文件
- 变换不变性