二叉树的数据结构:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
构造二叉树的函数:
public TreeNode buildTree(int[] x, int index){
if(x == null)
return null;
if(index >= x.length)
return null;
TreeNode root = new TreeNode(x[index]);
root.left = buildTree(x,2 * index + 1);
root.right = buildTree(x,2 * index + 2);
return root;
}
leetcode 104.二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
解题思路:递归返回左子树和右子树中较大者,返回时深度+1
public TreeNode buildTree(int[] x, int index){
if(x == null)
return null;
if(index >= x.length)
return null;
TreeNode root = new TreeNode(x[index]);
root.left = buildTree(x,2 * index + 1);
root.right = buildTree(x,2 * index + 2);
return root;
}
leetcode 110.平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
接上题二叉树的最大深度,比较左子树和右子树的深度
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
int a = maxDepth(root.left);
int b = maxDepth(root.right);
if( a - b > 1 || b - a > 1)
return false;
return isBalanced(root.left) && isBalanced(root.right);
}
leetcode 102.二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
解题思路:利用队列先进先出的特点,节点出列的同时将左&右子节点入列
leetcode 103.二叉树的锯齿形层次遍历
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
解题思路:接上题,判断本层为偶数层时翻转节点数据
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null)
return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int level = 0;
while (queue.isEmpty() == false) {
List<Integer> row = new ArrayList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
row.add(temp.val);
if (temp.left != null)
queue.add(temp.left);
if (temp.right != null)
queue.add(temp.right);
}
level++;
if (level % 2 == 0) {
Collections.reverse(row);
}
res.add(row);
}
return res;