LeetCode Symmetric Tree

 1 class Solution {

 2 public:

 3     bool isSymmetric(TreeNode *root) {

 4         if (root == NULL) return true;

 5         return dfs(root->left, root->right);

 6     }

 7     

 8     bool dfs(TreeNode* curnode, TreeNode* symnode) {

 9         if (curnode == NULL && symnode == NULL) return true;

10         if (curnode != NULL && symnode != NULL && curnode->val == symnode->val) {

11             return dfs(curnode->left, symnode->right) && dfs(curnode->right, symnode->left);

12         }

13         return false;

14     }

15     

16     bool _isSymmetric(TreeNode *root) {

17         if (root == NULL) return true;

18         vector<TreeNode*> sa;

19         vector<TreeNode*> sb;

20         sa.push_back(root->left);

21         sb.push_back(root->right);

22 

23         while (!sa.empty() && !sb.empty()) {

24             TreeNode* anode = sa.back();

25             TreeNode* bnode = sb.back();

26 

27             sa.pop_back();

28             sb.pop_back();

29             

30             if (anode == NULL && bnode == NULL) {

31                 continue;

32             }

33             

34             if (anode != NULL && bnode != NULL && anode->val == bnode->val) {

35                 sa.push_back(anode->left);

36                 sb.push_back(bnode->right);

37 

38                 sa.push_back(anode->right);

39                 sb.push_back(bnode->left);

40             } else {

41                 return false;

42             }

43         }

44         if (sa.size() != sb.size()) return false;

45         return true;

46     }

47 };

同时对左右子树进行遍历,只不过因为是对称的所以遍历时节点顺序要交换一下。如果是对称的,那么遍历节点应该一一对应,如果中间出现不一致则不对称。

第二轮:

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
只回忆起递归版本
/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    bool isSymmetric(TreeNode *root) {

        if (root == NULL) {

            return true;

        }

        return isSymmetric(root->left, root->right);

    }

    

    bool isSymmetric(TreeNode* root, TreeNode* symRoot) {

        if (root == NULL && symRoot == NULL) {

            return true;

        }

        if (root == NULL || symRoot == NULL) {

            return false;

        }

        if (root->val != symRoot->val) {

            return false;

        }

        

        return isSymmetric(root->left, symRoot->right) && isSymmetric(root->right, symRoot->left);

    }

};

 

你可能感兴趣的:(LeetCode)