"same tree" and "Delete Node in a Linked List"

来源:互联网 发布:软件平台招商 编辑:程序博客网 时间:2024/06/06 07:47

same tree:

  1. /** 
  2.  * Definition for binary tree 
  3.  * struct TreeNode { 
  4.  *     int val; 
  5.  *     TreeNode *left; 
  6.  *     TreeNode *right; 
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
  8.  * }; 
  9.  */  
  10. class Solution {  
  11. public:  
  12.     bool isSameTree(TreeNode *p, TreeNode *q) {  
  13.         // Start typing your C/C++ solution below  
  14.         // DO NOT write int main() function  
  15.         if (p == NULL && q == NULL)  
  16.             return true;  
  17.         else if (p == NULL || q == NULL)  
  18.             return false;  
  19.         return p->val == q->val && isSameTree(p->left, q->left)  
  20.             && isSameTree(p->right, q->right);  
  21.     }  
  22. };  
首先判断两根指针都为空或是有一个为空。然后通过&&运算符将递归过程中的false情况传递回最外层递归,从而实现只要递归过程中出现一次节点不相等,最后的返回结果就是false。


Delete Node in a Linked List:

  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode *next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public void deleteNode(ListNode *node) {  
  11.         //input check  
  12.         node->val = node->next->val;  
  13.         node->next = node->next->next;  
  14.     }  
由于是单向链表,在只给一个节点的情况下得不到前一个节点的信息,不能用常规的将前一个指针指向后一个指针的方法删除节点,这时候可以将下一个节点的信息复制到当前节点,然后用常规方法删除下一个节点。

0 0
原创粉丝点击