树问题规律总结
出现树问题,多数情况都是需要递归遍历(dfs和bfs),并且要根据题目要求,来思考相关的树的性质:
二叉树的一些性质
问题汇总
1. Leet Code OJ 101. Symmetric Tree
程序:
/**
* 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 isSymmetric(TreeNode root) {
if(root == null) return true;
return isMiror(root.left, root.right);
}
public boolean isMiror(TreeNode p, TreeNode q){
if(p == null && q == null) return true;
else if(p == null || q == null) return false;
boolean result = ((p.val == q.val) && isMiror(p.left, q.right) && isMiror(p.right, q.left));
return result;
}
}
107. Binary Tree Level Order Traversal II
问题
给定一个二叉树,返回自下而上的顺序遍历其节点值。 (即,从左到右,从叶到根的逐级)。
例如:给定下列二叉树
3
/ \
9 20
/ \
15 7
输出:
[
[15,7],
[9,20],
[3]
]
解析
可以考虑通过层次遍历二叉树,并通过一个curSize,来记录当前层的节点数,每遍历完一层就把该层的List放入结果集,然后清空List,进入下一层。最后反转结果集
代码
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<TreeNode> queue = new LinkedList<>();
List<List<Integer>> resultList = new ArrayList<>();
if(root == null) return resultList;
//处理根节点
queue.offer(root);
List<Integer> r = new ArrayList<>(Arrays.asList(new Integer[]{root.val}));
resultList.add(r);
List<Integer> temp = new ArrayList<>();
int curSize = queue.size();
//层次遍历二叉树
while(!queue.isEmpty()){
//用curSize来记录每一层次有多少节点
if(curSize <= 0){
resultList.add(temp);
temp = new ArrayList<>();
curSize = queue.size();
continue;
}
TreeNode node = queue.poll();
TreeNode left = node.left;
if(left != null){
temp.add(left.val);
queue.add(left);
}
TreeNode right = node.right;
if(right != null) {
temp.add(right.val);
queue.add(right);
}
//处理完一个节点
curSize--;
}
Collections.reverse(resultList);
return resultList;
}
}
108. Convert Sorted Array to Binary Search Tree
问题:
给定一个升序排序的数组,转换成一个平衡二叉树
分析:
平衡二叉树,首先是一棵二叉排序树;看到数组、排序这两个关键词,我们就要联想到排序队列的查找算法,我们这里就用到了二分的思想,用每一个中间值,作为当前的节点,这样就能得到平衡的平衡二叉树
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0){
return null;
}
return balance(nums, 0, nums.length-1);
}
public TreeNode balance(int[] nums, int left, int high){
if(left > high){
return null;
}
int mid = (left + high) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = balance(nums, left, mid-1);
node.right = balance(nums, mid+1, high);
return node;
}
}