235. Lowest Common Ancestor of a Binary Search Tree&&236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:windows7旗舰版优化 编辑:程序博客网 时间:2024/05/01 07:52
并不想赘述题……直接记代码。
235是一个二叉搜索树,那么很明显可以利用的条件就是左边小,右边大。我用的是递归。需要注意的是二叉树要记得考虑NULL的特殊情况。
class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(p==NULL||q==NULL||root==NULL) return NULL;//哎呀这次又忘记考虑特殊情况了啊 if(p->val>root->val&&q->val>root->val) return lowestCommonAncestor(root->right,p,q); if(p->val<root->val&&q->val<root->val) return lowestCommonAncestor(root->left,p,q); return root; }};
236是一个单纯的二叉树,依然可以用递归的方式来解决。
class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root == NULL || root == p || root == q) return root; //查看左子树中是否有目标结点,没有为null TreeNode* left = lowestCommonAncestor(root->left, p, q); //查看右子树是否有目标节点,没有为null TreeNode* right = lowestCommonAncestor(root->right, p, q); //都不为空,说明做右子树都有目标结点,则公共祖先就是本身 if(left!=NULL&&right!=NULL) return root; //如果发现了目标节点,则继续向上标记为该目标节点 return left == NULL ? right : left; }};这两道题都有另一种非递归的方式来解决,然而我试了一下每次都WA……也搞不清楚leetcode的输入到底是先序中序还是后序,分析不出来哪里有问题……
所以这个坑日后再补……
0 0
- 235. Lowest Common Ancestor of a Binary Search Tree&236. Lowest Common Ancestor of a Binary Tree
- 235. Lowest Common Ancestor of a Binary Search Tree&&236. Lowest Common Ancestor of a Binary Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- 235.Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- 项目版本控制
- Linux学习笔记:SQLyog链接linux虚拟机上的mysql数据库
- SGU105【找规律】
- game design原理系列学习笔记(四)
- Maven自动生成可运行jar包并将依赖的jar包一起打包
- 235. Lowest Common Ancestor of a Binary Search Tree&&236. Lowest Common Ancestor of a Binary Tree
- ios 各种证书 详解
- bzoj 4597: [Shoi2016]随机序列
- iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD
- This is usually because the "vboxsf" file system is not available.
- 阅读下面类的定义,请说出在测试函数中的不同情况的调用产生的结果1
- java 异步操作数据库
- 移动端app开发,框架的选择。
- 解决Eclipse Debug 的source not found问题