leetcode@ [236] Lowest Common Ancestor of a Binary Tree(Tree)
2016-01-03 16:06
267 查看
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
leetcode: 236
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void findPath(TreeNode* root, vector<TreeNode* >& load, vector<TreeNode* >& path, TreeNode* p) { if(root == NULL) return; if(root == p) { path = load; return; } load.push_back(root->left); findPath(root->left, load, path, p); load.pop_back(); load.push_back(root->right); findPath(root->right, load, path, p); load.pop_back(); } void reverse_vector(vector<TreeNode* > v) { vector<TreeNode* > res; res.clear(); for(int i=v.size()-1;i>=0;--i) res.push_back(v[i]); v = res; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(p == q) return p; vector<TreeNode* > load1, load2, path1, path2; TreeNode *r = root; load1.push_back(r); load2.push_back(r); findPath(r, load1, path1, p); findPath(r, load2, path2, q); reverse_vector(path1); reverse_vector(path2); int i = 0, j = 0, m = path1.size(), n = path2.size(), resi; cout << m << n << endl; while(i < m && j < n && path1[i] == path2[j]) { resi = i; ++i; ++j; } return path1[resi]; } };
leetcode: 236
相关文章推荐
- 嵌入式声卡应用分析---18
- uva 10054 项链
- Linux多线程实践(7) --Posix条件变量
- TCP/IP入门--TCP/IP的概念
- Android之获取view 、window之间的间距区域
- xgboost入门以及windows下安装及使用二
- Linux多线程实践(6) --Posix读写锁(解决读者写者问题)
- XenDesktop中如何重定向USB设备
- VS2010运行正常的控制台程序在VS2015中出现乱码的解决方法
- 1.3tableView向左滑动出现多个按钮操作
- hadoop hbase 集群的安装(未整理,先记录在这)
- Android 启动流程简介
- 【Windows Form 实战】学生成绩管理系统(二) 数据准备
- codevs 2645 Spore
- 计算s=(2^2)!+(3^2)! (函数的嵌套调用)
- 【LWJGL2 WIKI】【辅助库篇】Slick-Util库:第一部分-读取图片
- hibernate复合主键中为什么要复写equals和hashcode方法?还要implement Serializable?
- Linux多线程实践(5) --Posix信号量与互斥量(解决生产者消费者问题)
- C#基础之运算符二
- ARC内存管理机制详解