654. 最大二叉树
public TreeNode ConstructMaximumBinaryTree(int[] nums) {
if (nums.Length == 1) return new TreeNode(nums[0]);
int maxValue = Int32.MinValue;
int index = 0;
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] > maxValue)
{
maxValue = nums[i];
index = i;
}
}
TreeNode node = new TreeNode(maxValue);
if (index > 0)
{
int[] left = new int[index];
for (int i = 0; i < index; i++)
{
left[i] = nums[i];
}
node.left = ConstructMaximumBinaryTree(left);
}
if (index < nums.Length - 1)
{
int[] right = new int[nums.Length - index-1];
for (int i = 0; i < nums.Length - index - 1; i++)
{
right[i] = nums[index+i+1];
}
node.right = ConstructMaximumBinaryTree(right);
}
return node;
}
617. 合并二叉树
public TreeNode MergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null && root2 == null) return null;
if(root1 == null && root2 != null) return root2;//只要有一方为null,就返回另一方
if(root1 != null && root2 == null) return root1;//只要有一方为null,就返回另一方
TreeNode node = new TreeNode(0);
node.val = root1.val + root2.val;
if(root1.left != null || root2.left != null)
{
node.left = MergeTrees(root1.left, root2.left);
}
if(root1.right != null || root2.right != null)
{
node.right = MergeTrees(root1.right, root2.right);
}
return node;
}
700. 二叉搜索树中的搜索
public TreeNode SearchBST(TreeNode root, int val) {
if(root == null) return null;
if(root.val == val) return root;
else if(root.val > val) return SearchBST(root.left, val);
else return SearchBST(root.right, val);
}
98. 验证二叉搜索树
误区:
思路:需要一个全局的变量记作maxValue,使得中序遍历的过程中,不断更新最大值。
public class Solution {
private long maxVal = Int64.MinValue;//因为节点值最小为Int32.MinValue
public bool IsValidBST(TreeNode root) {
if(root == null) return true;
bool left = IsValidBST(root.left);
if(maxVal < root.val) maxVal = root.val;
else return false;
bool right = IsValidBST(root.right);
return left && right;
}
}