/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
#30. Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
class Solution { public int maxDepth(TreeNode root) { return findMaxHeight(root, 1); }
private int findMaxHeight(TreeNode node, int k) { if (node == null) { return k-1; }
int leftMaxLevel = findMaxHeight(node.left, k+1); int rightMaxLevel = findMaxHeight(node.right, k+1);
return Math.max(leftMaxLevel, rightMaxLevel); }}
#31. Same Tree
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
class Solution { public boolean isSameTree(TreeNode root1, TreeNode root2) { if (root1 == null || root2 == null) { return root1 == root2; } if (root1.val == root2.val) { return isSameTree(root1.left, root2.left) && isSameTree(root1.right, root2.right); } return false; }}
#32. Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its root.
class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; }
TreeNode leftAux = root.left; root.left = root.right; root.right = leftAux;
invertTree(root.left); invertTree(root.right);
return root; }}
Niciun comentariu:
Trimiteți un comentariu