day06
剑指 Offer 32 - I. 从上到下打印二叉树
题目描述:
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//来自评论区:这其实就是树的层序遍历,层序遍历需要用到队列,要在队列中删除一个节点,就将节点的左右孩子入队,
class Solution {
int [] tree=new int[1010];
int i=0;
//List<Integer> list=new ArrayList<Integer>();
// 队列的函数不用自己写
Queue<TreeNode> queue=new LinkedList<>();//队列
public int[] levelOrder(TreeNode root) {
if(root==null) return new int[0];
queue.add(root);
while(!queue.isEmpty()){
TreeNode node=queue.poll();//第一个结点从队列出队,并保存起来
//list.add(node.val);
tree[i++]=node.val;
if(node.left!=null){
queue.add(node.left);
//list.add(node.left.val);
}
if(node.right!=null){
queue.add(node.right);
//list.add(node.right.val);
}
}
int []tree1=new int[i];
for(int j=0;j<tree1.length;j++){
if(tree[j]!=0){
tree1[j]=tree[j];
}
}
return tree1;
}
}
day07
剑指 Offer 27. 二叉树的镜像
题目描述:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/er-cha-shu-de-jing-xiang-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode tn;
public TreeNode mirrorTree(TreeNode root) {
tn=root;
//if(root==null) return root;
if(root!=null){
getRoot(root);
}
// while(root.left!=null||root.right!=null){
// tree=root.left;
// root.left=root.right;
// root.right=tree;
// }
return tn;
}
public void getRoot(TreeNode t){
//if(t==null) return t;
// else if(t.left==null&&t.right==null){
// return t;
// }
if(t!=null){//t.left!=null||t.right!=null
TreeNode tree=t.left;
t.left=t.right;
t.right=tree;
getRoot(t.left);
getRoot(t.right);
}
}
}
注:day06/day07都只做了一题