The Solution to Leetcode 101 Symmetric Tree
来源:互联网 发布:大闹天宫数据库密码 编辑:程序博客网 时间:2024/06/06 05:02
Question:
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思路:
判断一个二叉树是不是对称二叉树。
1.左右节点为空,是。
2.左节点为空,右节点非空,不是。
3.左节点非空,右节点为空,不是。
4.左右节点都非空,但值不相等,不是。
用递归的方法继续判断。
Answer:
/** * 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) { if(root==NULL) return true; else return testSymmetric(root->left,root->right); } bool testSymmetric(TreeNode* left, TreeNode* right) { //1.左右节点都为空 if(left==NULL&&right==NULL) return true; //左节点为空,右节点非空 else if(left==NULL&&right!=NULL) return false; //左节点非空,右节点为空 else if(left!=NULL&&right==NULL) return false; //左右节点都非空,但值不相等 else if(left!=NULL&&right!=NULL&&left->val!=right->val) return false; else return testSymmetric(left->left,right->right)&&testSymmetric(left->right,right->left); } };
Run code result:
Your input
[1,2,2,3,4,4,3]
Your answer
true
Expected answer
true
阅读全文
0 0
- The Solution to Leetcode 101 Symmetric Tree
- The Solution to LeetCode 111 Minimum Depth of Binary Tree
- The Solution to Leetcode 110 Balanced Binary Tree
- The Solution to Leetcode 563 Binary Tree Tilt
- LeetCode(101)Symmetric Tree
- LeetCode 101 Symmetric Tree
- LeetCode: Symmetric Tree [101]
- [leetcode 101] Symmetric Tree
- [LeetCode 101]Symmetric Tree
- leetcode-101 Symmetric Tree
- leetcode || 101、Symmetric Tree
- Leetcode[101]-Symmetric Tree
- leetcode[101]:Symmetric Tree
- LeetCode 101 Symmetric Tree
- leetcode 101 Symmetric Tree
- Leetcode# 101 Symmetric Tree
- leetcode 101: Symmetric Tree
- leetCode #101 Symmetric Tree
- Mysql提示Column count doesn't match value count at row 1
- 小米手机,测试时应用图标不能更改,还出现偶尔应用版本还原
- 顺序播放效果js实现小窍门
- unity接入微信支付-Ios篇
- Tensorflow 搭建简单神经网络 | Python
- The Solution to Leetcode 101 Symmetric Tree
- JDBC连接数据库的代码及步骤
- 不同操作系统之间的网络配置
- Java实现-不同的路径1
- iframe页面中父页面跟子页面方法的相互调用
- weblogic发布程序中遇到的问题
- git 代码统计
- tensorflow54 《TensorFlow技术解析与实战》15 TensorFlow线性代数编译框架XLA
- IntelliJ IDEA 使用SSH Terminal