20200305
题目 :从上到下打印二叉树 |||
实现一个函数按照之字型顺序打印二叉树,即第一行按照从左到右的顺序打印;第二层按照从右到左的顺序打印,以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
思路 :利用一个数记录是多少行,偶数行对列表进行翻转。
class Solution{
public List<List<Integer>> levelOrder(TreeNode root){
List<List<Integer>> resList = new ArrayList<>();
if(root == null) return resList;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int num=0;
while(!queue.isEmpty()){
num++;
int size = queue.size();
List<Integer> list = new ArrayList<>();
for(int i=0;i<size;i++){
TreeNode curNode = queue.poll();
list.add(curNode.val);
if(curNode.left != null) queue.add(curNode.left);
if(curNode.right != null) queue.add(curNode.right);
}
if(num%2==0) Collections.reverse(list);
resList.add(list);
}
return resList;
}
}
题目 :二叉搜索树的后续遍历
输入一个整数数组,判断该数字是不是某二叉树的后续遍历结果。如果是则返回true
,否则返回false
。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6,5]
输出: true
思路 :找到根节点,递归方式。
code
class Solution{
public boolean verifyPostorder(int[] postorder){
if(postorder.length == 1){
return true;
}
if(postorder.length == 0){
return true;
}
boolean flag = verify(postorder,0,postorder.length-1);
return flag;
}
public boolean verify(int[] postorder, int left, int right){
if(right <= left){
return true;
}
int temp = left;
//找到第一个大于根节点的值
while((temp < right)&&(postorder[temp]<postorder[right])){
temp++;
}
//判断后面是否都大于根节点
for(int i=temp;i<right;i++){
if(postorder[i] < postorder[right]){
return false;
}
}
//递归
return verify(postorder,left,temp-1) && verify(postorder,temp,right-1);
}
}
题目 :二叉树中和为某一值的路径
输入一颗二叉树和一个整数,打印出二叉树中节点值得和为输入整数的所有路径。从树的根节点开始往下知道叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
code :
class Solution{
private List<List<Integer>> ans;
public List<List<Integer>> pathSum(TreeNode root,int sum){
ans = new ArrayList<>();
if(root == null) return ans;
pathSumHelper(new ArrayList<Integer>(),root,sum,0);
return ans;
}
private void pathSumHelper(List<Integer> path, TreeNode root,int sum,int cur){
cur += root.val;
path.add(root.val);
if(sum == cur && root.left == null && root.right == null){
ans.add(new ArrayList(path));
}
if(root.left != null){
pathSumHelper(path,root.left,sum,cur);
path.remove(path.size() - 1);//将入栈,已经遍历的节点取出。
}
if(root.right != null){
pathSumHelper(path,root.right,sum,cur);
path.remove(path.size() - 1);
}
}
}