Leetcode 235:
题目的第一想法:
这道题的需要找的是两个节点的最低共同祖先。我的第一想法是先找到一个在range内的数字,但我并不是很确定我第一个找到的数字是否为最低共同祖先。另外一个卡住我的点在于对于两个最低节点,我猜测leetcode是随机分配的。也就是说p可能是更小数字,也可能是更大的数字。所以在检查的时候应该同时检查两个数字来避免nullpointerexception的发生。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}
看完代码随想录之后的想法:
感觉这道题是否能发现第一个遍历到的数字就是最低共同祖先是一个坎
Leetcode 701:
题目的第一想法:
这道题很简单,因为并不涉及到树的rebalance。所以只要找到最正确的位置加入节点就好。然后节点分为leaf,之包含一个子树的节点。在遍历的过程中还需要想到遍历的方式。到底是遍历一条分叉还是需要遍历全树。
class Solution {
TreeNode curRoot;
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
insert(root, val);
return root;
}
void insert(TreeNode root, int val){
if(root == null) return;
if(root.left == null && root.right == null){
if(val > root.val){
root.right = new TreeNode(val);
}else{
root.left = new TreeNode(val);
}
}else if(root.left == null && val < root.val){
root.left = new TreeNode(val);
}else if(root.right == null && val > root.val){
root.right = new TreeNode(val);
}else{
if(val > root.val){
insert(root.right, val);
}else{
insert(root.left, val);
}
}
}
}
看完代码随想录之后的想法:
这道题我写麻烦了。相当于结合了递归和迭代各自麻烦的部分。导致并没能发挥两者的优点。其实递归/迭代都各自起来有更好的loop方式。
Leetcode 450:
题目的第一想法:
这道题我的第一想法是搞清楚删除节点的逻辑和需要的variable。删除节点的逻辑是找到需要被删除的节点,此时可以选择一个子节点提上来和父节点相连,然后把没有被选择的子节点挂在当前节点的正确的一侧。比如如果我选择提右节点,那么左节点就应该被移到新左节点的最右侧。同理如果我选择提左节点,那么右节点就应该被移到新右节点的最左侧。同时节点的状况可以双子树都存在,之存在一个子树和leaf,需要对各自的情况作具体分析。另外一个困扰住我的点是我需要得知variable,也就是父节点的信息来做连接。但其实通过递归可以规避掉这个问题。
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return null;
if(root.val == key){
if(root.right == null && root.left == null) return null;
else if(root.left == null) return root.right;
else if(root.right == null) return root.left;
else{
TreeNode cur = root;
cur = cur.left;
while(cur.right != null) cur = cur.right;
cur.right = root.right.left;
root.right.left = root.left;
return root.right;
}
}
if(root.val > key) root.left = deleteNode(root.left, key);
else if(root.val < key)root.right = deleteNode(root.right, key);
return root;
}
}
看完代码随想录之后的想法:
这道题我对比了好久,也没太能发现我和卡哥的代码的区别是什么。为什么只需要走一层就好了