mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update226.翻转二叉树,简化C#代码
This commit is contained in:
@ -1018,25 +1018,13 @@ public class Solution {
|
||||
```csharp
|
||||
//迭代
|
||||
public class Solution {
|
||||
public TreeNode InvertTree(TreeNode root) {
|
||||
if (root == null) return null;
|
||||
Stack<TreeNode> stack=new Stack<TreeNode>();
|
||||
stack.Push(root);
|
||||
while(stack.Count>0)
|
||||
{
|
||||
TreeNode node = stack.Pop();
|
||||
swap(node);
|
||||
if(node.right!=null) stack.Push(node.right);
|
||||
if(node.left!=null) stack.Push(node.left);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
public void swap(TreeNode node) {
|
||||
TreeNode temp = node.left;
|
||||
node.left = node.right;
|
||||
node.right = temp;
|
||||
}
|
||||
public TreeNode InvertTree(TreeNode root) {
|
||||
if(root == null) return root;
|
||||
(root.left,root.right) = (root.right, root.left);
|
||||
InvertTree(root.left);
|
||||
InvertTree(root.right);
|
||||
return root;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user