Leetcode-101。対称二分木(C ++)

Leetcode 101 Symmetric Binary Tree

画像
アイデア1:
再帰的

/** * Definition for a binary tree node. * struct TreeNode { * int val * TreeNode *left * TreeNode *right * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * } */ class Solution { public: bool test(TreeNode* root1,TreeNode* root2) { if(root1==NULL&&root2==NULL) { return true } if(root1==NULL||root2==NULL) { return false } return (root1->val==root2->val)&&test(root1->left,root2->right)&&test(root1->right,root2->left) } bool isSymmetric(TreeNode* root) { return test(root,root) } }

アイデア2:
反復



/** * Definition for a binary tree node. * struct TreeNode { * int val * TreeNode *left * TreeNode *right * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * } */ class Solution { public: bool isSymmetric(TreeNode* root) { queue<TreeNode*> queue_T TreeNode* root1 TreeNode* root2 if(root==NULL) { return true } else { queue_T.push(root) queue_T.push(root) while(queue_T.size()!=0) { root1=queue_T.front() queue_T.pop() root2=queue_T.front() queue_T.pop() if(root1==NULL&&root2==NULL) { continue } if(root1==NULL||root2==NULL) { return false } if(root1->val!=root2->val) { return false } else { queue_T.push(root1->left) queue_T.push(root2->right) queue_T.push(root1->right) queue_T.push(root2->left) } } return true } } }