236. Lowest Common Ancestor of a Binary Tree LeetCode
来源:互联网 发布:淘宝平台服务协议 编辑:程序博客网 时间:2024/05/17 01:35
题意:求二叉树上两个节点p,q的最近公共祖先。
题解:dfs求解,当遍历到p或者q的时候往上返回p或者q,否则返回NULL,当遇到第一个左右子树都有返回值的那个节点时,就找到了他们的最近公共祖先。
/** * 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 NULL; if(root == p || root == q) return root; TreeNode *left = lowestCommonAncestor(root->left,p,q); TreeNode *right = lowestCommonAncestor(root->right,p,q); if(left && right) return root; else if(left) return left; else return right; }};
0 0
- [leetcode] 236.Lowest Common Ancestor of a Binary Tree
- [LeetCode]236.Lowest Common Ancestor of a Binary Tree
- [leetcode] 236.Lowest Common Ancestor of a Binary Tree
- [LeetCode]236. Lowest Common Ancestor of a Binary Tree
- 236. Lowest Common Ancestor of a Binary Tree LeetCode
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree
- leetcode 236. Lowest Common Ancestor of a Binary Tree
- LeetCode-236.Lowest Common Ancestor of a Binary Tree
- LeetCode 236. Lowest Common Ancestor of a Binary Tree
- LeetCode *** 236. Lowest Common Ancestor of a Binary Tree
- leetcode.236. Lowest Common Ancestor of a Binary Tree
- LeetCode - 236. Lowest Common Ancestor of a Binary Tree
- LeetCode 236. Lowest Common Ancestor of a Binary Tree
- [LeetCode] 236. Lowest Common Ancestor of a Binary Tree
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree
- Leetcode 236. Lowest Common Ancestor of a Binary Tree
- Leetcode 236. Lowest Common Ancestor of a Binary Tree
- Leetcode-236. Lowest Common Ancestor of a Binary Tree
- java中StringBuilder、StringBuffer、String类之间的关系 - 音
- 使用二维数组查询省份
- Educational Codeforces Round 9 E. Thief in a Shop(FFT)
- erlang趣事之二进制型与位于法
- HTML5 canvas绘制雪花飘落动画(需求分析、知识点、程序编写分布详解)
- 236. Lowest Common Ancestor of a Binary Tree LeetCode
- android实现socket连接(服务器端)
- [LightOJ 1031]Easy Game[DP]
- 使用JMeter进行负载测试——终极指南
- 慕课网自学 关于ListView 的配适器
- 华为vlan test(一)
- shell重定向小记
- 数据存储之SharedPreferences
- 时序约束