树的遍历,
递归:
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 isSymmetric(TreeNode *root) {13 // Start typing your C/C++ solution below14 // DO NOT write int main() function15 if (root == NULL)16 return true;17 return symmetric(root->left, root->right);18 }19 bool symmetric(TreeNode *lnode, TreeNode *rnode) {20 if (lnode == NULL && rnode == NULL)21 return true;22 if (lnode == NULL || rnode == NULL) 23 return false;24 if (lnode->val != rnode->val) {25 return false;26 }27 return symmetric(lnode->left, rnode->right) && symmetric(lnode->right, rnode->left);28 }29 };
迭代要用到队列;
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 isSymmetric(TreeNode *root) {13 // Start typing your C/C++ solution below14 // DO NOT write int main() function15 if (root == NULL)16 return true;17 queuetqueue;18 tqueue.push(root->left);19 tqueue.push(root->right);20 while (!tqueue.empty()) {21 TreeNode *lnode = tqueue.front();22 tqueue.pop();23 TreeNode *rnode = tqueue.front();24 tqueue.pop();25 if (lnode == NULL && rnode == NULL)26 continue;27 if (lnode == NULL || rnode == NULL || (lnode->val != rnode->val))28 return false;29 tqueue.push(lnode->left);30 tqueue.push(rnode->right);31 tqueue.push(lnode->right);32 tqueue.push(rnode->left);33 }34 return true;35 }36 };