236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:万国数据招聘 编辑:程序博客网 时间:2024/05/16 14:56
考察点:DFS;
思路:首先根据一个搜索出到两个指针所指对象的path,存放在vector中,然后反转该vector,前面的元素是从根节点出发的节点路径,找出第一个不同的元素,返回之前的元素就可;
C++ 代码:
/** * 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: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root==NULL ) return root; vector<TreeNode*> p_path, q_path; if (DFS(root, p, p_path)) { reverse(p_path.begin(), p_path.end()); } if (DFS(root, q, q_path)) { reverse(q_path.begin(), q_path.end()); } int i=0; while(p_path[i] == q_path[i] && i<p_path.size() && i<q_path.size()) i++; return p_path[i-1]; } bool DFS(TreeNode* node, TreeNode* target, vector<TreeNode*> & path) { if (node == target) { path.push_back(node); return true; } if (node == NULL) { return false; } if (DFS(node->left, target, path) || DFS(node->right, target, path)) { path.push_back(node); return true; } return false; }};
另外discuss里面的大神写法:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root || root == p || root == q) return root; TreeNode* left = lowestCommonAncestor(root->left, p, q); TreeNode* right = lowestCommonAncestor(root->right, p, q); return !left ? right : !right ? left : root;}
阅读全文
0 0
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree(***)
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Matplotlib 教程
- Java中守护线程的总结
- dynamic_rnn的参数time_major
- unity 代码绑定传参数的button程序
- php获取真实ip地址原理及实现
- 236. Lowest Common Ancestor of a Binary Tree
- 如何区分JAVA的编码格式
- 指针函数和函数指针
- 小字典之MFC简单的多线程调用类的成员函数实现逐步画线功能 VS2015 C++ 完成
- Glide按照原尺寸显示网络图片
- Jquery调用打印机打印(包含去除页眉页脚)
- 解决spring boot 拦截器中无法注入serivce
- Oracle对in的处理
- whose view is not in the window hierarchy!