"same tree" and "Delete Node in a Linked List"
2016-05-25 11:17
555 查看
same tree:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (p == NULL && q == NULL)
return true;
else if (p == NULL || q == NULL)
return false;
return p->val == q->val && isSameTree(p->left, q->left)
&& isSameTree(p->right, q->right);
}
};
首先判断两根指针都为空或是有一个为空。然后通过&&运算符将递归过程中的false情况传递回最外层递归,从而实现只要递归过程中出现一次节点不相等,最后的返回结果就是false。
Delete Node in a Linked List:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode *next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode
*node) {
//input check
node->val = node->next->val;
node->next = node->next->next;
}
由于是单向链表,在只给一个节点的情况下得不到前一个节点的信息,不能用常规的将前一个指针指向后一个指针的方法删除节点,这时候可以将下一个节点的信息复制到当前节点,然后用常规方法删除下一个节点。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (p == NULL && q == NULL)
return true;
else if (p == NULL || q == NULL)
return false;
return p->val == q->val && isSameTree(p->left, q->left)
&& isSameTree(p->right, q->right);
}
};
首先判断两根指针都为空或是有一个为空。然后通过&&运算符将递归过程中的false情况传递回最外层递归,从而实现只要递归过程中出现一次节点不相等,最后的返回结果就是false。
Delete Node in a Linked List:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode *next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode
*node) {
//input check
node->val = node->next->val;
node->next = node->next->next;
}
由于是单向链表,在只给一个节点的情况下得不到前一个节点的信息,不能用常规的将前一个指针指向后一个指针的方法删除节点,这时候可以将下一个节点的信息复制到当前节点,然后用常规方法删除下一个节点。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解