LeetCode: Symmetric 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 dfs(TreeNode *left, TreeNode *right) { 13 if (!left && !right) return true; 14 if (!left || !right) return false; 15 return left->val == right->val && dfs(left->left, right->right) && dfs(left->right, right->left); 16 } 17 bool isSymmetric(TreeNode *root) { 18 // Start typing your C/C++ solution below 19 // DO NOT write int main() function 20 if (!root) return true; 21 return dfs(root->left, root->right); 22 } 23 };
下面是自己写的iterasive的法子
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 if (!root) return true; 14 queue<TreeNode*> ltr, rtl; 15 ltr.push(root), rtl.push(root); 16 while (!ltr.empty() && !rtl.empty()) { 17 TreeNode *ltrfront = ltr.front(); 18 TreeNode *rtlfront = rtl.front(); 19 ltr.pop(), rtl.pop(); 20 if (!ltrfront && !rtlfront) continue; 21 if (!ltrfront || !rtlfront || ltrfront->val != rtlfront->val) return false; 22 ltr.push(ltrfront->left), ltr.push(ltrfront->right); 23 rtl.push(rtlfront->right), rtl.push(rtlfront->left); 24 } 25 return ltr.empty() && rtl.empty(); 26 } 27 };
C#
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public bool IsSymmetric(TreeNode root) { 12 if (root == null) return true; 13 Queue<TreeNode> ltr = new Queue<TreeNode>(); 14 Queue<TreeNode> rtl = new Queue<TreeNode>(); 15 ltr.Enqueue(root); 16 rtl.Enqueue(root); 17 while (ltr.Count > 0 && rtl.Count > 0) { 18 TreeNode ltrPeek = ltr.Peek(); 19 TreeNode rtlPeek = rtl.Peek(); 20 ltr.Dequeue(); 21 rtl.Dequeue(); 22 if (ltrPeek == null && rtlPeek == null) continue; 23 if (ltrPeek == null || rtlPeek == null || ltrPeek.val != rtlPeek.val) return false; 24 ltr.Enqueue(ltrPeek.left); 25 ltr.Enqueue(ltrPeek.right); 26 rtl.Enqueue(rtlPeek.right); 27 rtl.Enqueue(rtlPeek.left); 28 } 29 return ltr.Count == 0 && rtl.Count == 0; 30 } 31 }