226.翻转二叉树
使用前序遍历,每次递归都交换其左右节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution
{
public TreeNode InvertTree(TreeNode root)
{
if (root == null)
{
return root;
}
Swap(ref root.left, ref root.right);
InvertTree(root.left);
InvertTree(root.right);
return root;
}
void Swap(ref TreeNode a, ref TreeNode b)
{
TreeNode temp = a;
a = b;
b = temp;
}
}
101.对称二叉树
本题使用后续遍历,先收集左子树与右子树外侧比较的结果,再收集左子树与右子树内侧比较的结果,最后再将两个结果相与,即可得到答案。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution
{
public bool IsSymmetric(TreeNode root)
{
return Compare(root.left, root.right);
}
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;
}
bool outside = Compare(left.left, right.right);
bool inside = Compare(left.right, right.left);
bool result = outside && inside;
return result;
}
}
104.二叉树的最大深度
二叉树的最大深度和最大高度相等,因此我们可以用后序遍历的方式来计算二叉树的最大深度。先计算出左子树的最大深度,再计算出右子树的最大深度,最后取最大值即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution
{
public int MaxDepth(TreeNode root)
{
return GetHeight(root);
}
int GetHeight(TreeNode node)
{
if (node == null)
{
return 0;
}
int leftHeight = GetHeight(node.left);
int rightHeight = GetHeight(node.right);
int result = 1 + Math.Max(leftHeight, rightHeight);
return result;
}
}
111.二叉树的最小深度
本体思路与上题类似,不同的是需要对节的左右子树有一个为空的情况进行特殊处理。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution
{
public int MinDepth(TreeNode root)
{
return GetHeight(root);
}
int GetHeight(TreeNode node)
{
if (node == null)
{
return 0;
}
int leftHeight = GetHeight(node.left);
int rightHeight = GetHeight(node.right);
if (node.left != null && node.right == null)
{
return 1 + leftHeight;
}
if (node.left == null && node.right != null)
{
return 1 + rightHeight;
}
int result = 1 + Math.Min(leftHeight, rightHeight);
return result;
}
}
1227

被折叠的 条评论
为什么被折叠?



