mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Update101.对称二叉树,添加C#版
This commit is contained in:
@ -897,6 +897,53 @@ impl Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
### C#
|
||||
```C#
|
||||
// 递归
|
||||
public bool IsSymmetric(TreeNode root)
|
||||
{
|
||||
if (root == null) return true;
|
||||
return Compare(root.left, root.right);
|
||||
}
|
||||
public bool Compare(TreeNode left, TreeNode right)
|
||||
{
|
||||
if(left == null && right != null) return false;
|
||||
else if(left != null && right == null ) return false;
|
||||
else if(left == null && right == null) return true;
|
||||
else if(left.val != right.val) return false;
|
||||
|
||||
var outside = Compare(left.left, right.right);
|
||||
var inside = Compare(left.right, right.left);
|
||||
|
||||
return outside&&inside;
|
||||
}
|
||||
```
|
||||
``` C#
|
||||
// 迭代法
|
||||
public bool IsSymmetric(TreeNode root)
|
||||
{
|
||||
if (root == null) return true;
|
||||
var st = new Stack<TreeNode>();
|
||||
st.Push(root.left);
|
||||
st.Push(root.right);
|
||||
while (st.Count != 0)
|
||||
{
|
||||
var left = st.Pop();
|
||||
var right = st.Pop();
|
||||
if (left == null && right == null)
|
||||
continue;
|
||||
|
||||
if ((left == null || right == null || (left.val != right.val)))
|
||||
return false;
|
||||
|
||||
st.Push(left.left);
|
||||
st.Push(right.right);
|
||||
st.Push(left.right);
|
||||
st.Push(right.left);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
|
Reference in New Issue
Block a user