二叉树进阶题目记录
实现二叉树的非递归 先序, 中序, 后序遍历
非递归实现
二叉树的构建和遍历
题目描述:
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
import java.util.Scanner;
public class Main {
public static class TreeNode{
char val;
TreeNode leftNode;
TreeNode rightNode;
public TreeNode (char val){
this.val = val;
}
}
static int index = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
index = 0;
String s = in.nextLine();
char[] array = s.toCharArray();
TreeNode root = build(array);
inorder(root);
System.out.println();
}
}
//中序遍历
private static void inorder(TreeNode root) {
if(root == null){
return;
}
inorder(root.leftNode);
System.out.print(root.val + " ");
inorder(root.rightNode);
}
//先序构建
private static TreeNode build(char[] array) {
//叶子节点返回空值
if(array[index] == '#'){
return null;
}
// ABC##DE#G##F###
//中序 c b e g d f a
TreeNode root = new TreeNode(array[index]);
index++;
root.leftNode = build(array);
index++;
root.rightNode = build(array);
return root;
}
}
题目分析:
题目给定先序遍历字符串ABC##DE#G##F### 的字符串,要求使用这个字符串进行勾线一个二叉树.
先序遍历是以中左右的顺序遍历的,我们可以知道只有先序遍历结果是不能得出正确的二叉树结构的.但是题目给出了空节点的位置.
代码分析:
TreeNode root = new TreeNode(array[index]);
index++;
root.leftNode = build(array);
index++;
root.rightNode = build(array);
return root;
顺着先序遍历的顺序,从根节点开始递归创建节点,直到叶子结点 '# ',从叶子节点向上递归赋值,从而形成树的结构.
注意事项:
index值使用static关键字修饰,在面对多个样例的时候,要注意将其值重新赋值为0;
先序遍历可以使使用标号来判断位置(待补)
二叉树的分层遍历
在线OJ
和普通的分层遍历不同的是,这道题返回值要求使用List<List>结构作为返回值.所以在遍历过程中,我们需要进行销量小量的修改
/**
* 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 {
static List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
result = new ArrayList<>(