leetcode 101
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 101相关的知识,希望对你有一定的参考价值。
101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ 2 2
/ \ / 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ 2 2
\ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
判断二叉树是否为平衡二叉树。
递归实现。
代码如下:
1 /** 2 * Definition for a binary tree node. 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 == NULL) 14 { 15 return true; 16 } 17 return isSame(root->left, root->right); 18 } 19 bool isSame(TreeNode* left, TreeNode* right) 20 { 21 if(left == NULL && right == NULL) 22 { 23 return true; 24 } 25 else if(left == NULL) 26 { 27 return false; 28 } 29 else if(right == NULL) 30 { 31 return false; 32 } 33 34 if(left->val == right->val && left->left == NULL && left->right && right->right == NULL && right->left == NULL) 35 { 36 return true; 37 } 38 else if(left->val == right->val) 39 { 40 return isSame(left->left, right->right) && isSame(left->right, right->left); 41 } 42 else 43 { 44 return false; 45 } 46 47 } 48 };
以上是关于leetcode 101的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 101.对称二叉树 - JavaScript