[leetcode]Symmetric Tree (对称树 C语言实现)

来源:互联网 发布:打开链接就跳转到淘宝 编辑:程序博客网 时间:2024/05/07 01:57

Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
题意:判断二叉树是否是对称镜像树
Notes:若采用递归或迭代将会加分
解题思路:采用的是最笨的办法,把树的两个根分支分别用一个数组存储起来,然后通过比较两个数组对应值大小来判断二叉树时候是对称树。
C语言实现代码,很冗余,暂时还没有想到其他办法:

/**解题思路:申请两个数组用于存储左右分支树的值,然后比较数组得到值 * Definition for binary tree * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right;  * }; */void PreOrderL(struct TreeNode *root, int *arr, int *i){    (*i)++;     if(root == NULL){         *(arr + *i) = 0;         return;     }     *(arr + *i) = root->val;    PreOrderL(root->left,arr,i);//从左往右遍历    PreOrderL(root->right,arr,i); } void PreOrderR(struct TreeNode *root, int *arr, int *i){     (*i)++;     if(root == NULL){         *(arr + *i) = 0;         return;     }     *(arr + *i) = root->val;    PreOrderR(root->right,arr,i);//从右往左遍历    PreOrderR(root->left,arr,i); }bool isSymmetric(struct TreeNode *root) {    int i,j;    int r[1000],l[1000];    memset(r, 0, 1000*sizeof(int));    memset(l, 0, 1000*sizeof(int));    if(root == NULL){        return 1;    }    if(root->left == NULL && root->right == NULL){        return 1;    }    i = j = 0;    PreOrderL(root->left,l,&i);    PreOrderR(root->right,r,&j);    for(i = 0; i < 1000; i++){        if(l[i] != r[i]){            return 0;        }    }    return 1;}
0 0
原创粉丝点击