【LeetCode

【LeetCode OJ】Maximum Depth of Binary Tree

杀马特。学长 韩版系。学妹 提交于 2021-02-12 05:49:44
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private int max = 0; public void preOrder(TreeNode root, int depth){ if(root == null)return; preOrder(root.left, depth + 1); if(max < depth) max = depth; preOrder(root.right, depth + 1); } public int maxDepth(TreeNode root) { preOrder(root, 1); return max; } } 来源: oschina

【LeetCode OJ】Same Tree

ε祈祈猫儿з 提交于 2021-02-12 05:43:33
Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { return preOrder(p, q); } public boolean preOrder(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if((p == null && q != null) || (q == null && p != null)) return false; if(