[easy] Same Tree

难度: 简单 标题:相同二叉树

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.

判断两颗二叉树是否相同。

思路

递归,当左子树相同,右子树相同,值相同时两棵树相同。

取子树之前判断一下是否为 null。否则null.left,null.right,null.val会报错。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null || q == null){
if(p== null && q == null){
return true;
}else return false;
}
return p.val == q.val &&isSameTree(p.left,q.left)&&isSameTree(q.right,p.right);
}
}

链接

https://leetcode.com/problems/same-tree/

[easy] Maximum Depth of Binary Tree

难度: 简单 标题:二叉树最大深度

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.

思路

root == null时深度为0;最大深度为左/右的最大深度+1;

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return 1;
int DL = maxDepth(root.left);
int DR = maxDepth(root.right);
return (DL>DR?DL:DR)+1;

}
}

链接

https://leetcode.com/problems/maximum-depth-of-binary-tree/

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×