二叉树两结点的最低共同父结点
2016-05-12 00:14
239 查看
题目:二叉树的结点定义如下:
struct TreeNode
{
int m_nvalue;
TreeNode* m_pLeft;
TreeNode* m_pRight;
};
输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点。
struct TreeNode
{
int m_nvalue;
TreeNode* m_pLeft;
TreeNode* m_pRight;
};
输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点。
struct Node { int val; Node *left; Node *right; Node(int v) { val = v; left = right = NULL; } }; bool getPath(Node *root, Node *target, vector<Node*> &path) { if (root == NULL) { return false; } path.push_back(root); if (root == target) { return true; } bool left = getPath(root->left, target, path); if (left) { return true; } bool right = getPath(root->right, target, path); if (right) { return true; } path.pop_back(); return false; } Node* getCommonNode(vector<Node*> &path1, vector<Node*> &path2) { if (path1.empty() || path2.empty()) { return NULL; } int last = min(path1.size()-1, path2.size()-1); int i = last; int j = last; while (path1[i] != path2[j]) { i--; j--; } return path1[i]; } Node* getParent(Node *root, Node *p, Node *q) { vector<Node*> path1; vector<Node*> path2; bool a = getPath(root, p, path1); if (a) { bool b = getPath(root, q, path2); if (b) { return getCommonNode(path1, path2); } } return NULL; }
相关文章推荐
- win8.1安装mongodb
- c++第五次作业
- 微信对话框小三角形实现
- Leetcode Everyday: 242. Valid Anagram
- Wireshark抓包示范:TCP三次握手建立连接和四次握手断开连接
- 记录第一次纯手打爬虫经历
- 记录第一次纯手打爬虫经历
- Retrofit2.0使用总结及注意事项
- 探索《How Tomcat Works》心得(二)
- (三)映射对象标识符(OID)
- 小酌重构系列[10]——分离职责
- 里氏替换原则(Liskov Substitution Principle) LSP
- 小酌重构系列[10]——分离职责
- [Java] 基础命令
- Centos 7 学习之静态IP设置
- netfilter/iptables全攻略
- Install Sentry Server(Sentry Server的搭建)[for_wind]
- C 标准库 —— stdio.h
- CentOS7 下linux不能上网解决方法,centos7 eth0 没有ip,IP突然丢失
- nefu阶乘定理