合并二叉树:
递归算法,把每个节点都看作根节点,做三件事,val值加起来,合并左子树,合并右子树。
这里发现val值和null值可以直接加,TreeNode(root1.val+root2.val);
/**
* 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;
* }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null){
return root2;
}
if(root2 == null){
return root1;
}
TreeNode mergetrees = new TreeNode(root1.val+root2.val);
mergetrees.left = mergeTrees(root1.left, root2.left);
mergetrees.right = mergeTrees(root1.right, root2.right);
return mergetrees;
}
}
翻转二叉树:
这里注意不是比较val值是不是空,而是看整个节点、整棵树是不是空。
if(root.val == null){
return root;
}
//是错误的
和上一道题不同的是,这里不需要新建树。对当前树进行编辑。
/**
* 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;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root== null){
return root;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
计算二叉树深度:
使用递归,截止条件是当前节点为空,如果为空返回深度为0,否则深度为max(左子树,右子树)+1。
起初我的编写是错误的
提交后,对于[1,null,2]的输入,首先输入根节点1,发现不满足左右子树都为空,因此执行else,开始计算左子树深度,左子树为空,在第一层调用中if中执行null.left,发生错误。
class Solution {
int depth;
public int maxDepth(TreeNode root) {
if(root.left==null && root.right==null){
depth = 1;}
else{
depth=Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
return depth;
}
}
进行修改:
class Solution {
int depth;
public int maxDepth(TreeNode root) {
if(root==null){
depth = 0;}
else{
depth=Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
return depth;
}
}