首页 > 试题广场 >

实现二叉树先序,中序和后序遍历

[编程题]实现二叉树先序,中序和后序遍历
  • 热度指数:4199 时间限制:C/C++ 8秒,其他语言16秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
分别按照二叉树先序,中序和后序打印所有的节点。

输入描述:
第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。

以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)


输出描述:
输出三行,分别表示二叉树的先序,中序和后序。
示例1

输入

3 1
1 2 3
2 0 0
3 0 0

输出

1 2 3
2 1 3
2 3 1

备注:

import java.util.*;
import java.io.*;

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val){
        this.val = val;
    }
}

public class Main{
    
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] params1 = br.readLine().split(" ");
        int len = Integer.parseInt(params1[0]);
        Map<Integer,TreeNode> map = new HashMap<>();
        TreeNode head = new TreeNode(Integer.parseInt(params1[1]));
        map.put(Integer.parseInt(params1[1]),head);
        for(int i = 0;i < len; i++){
            String[] params2 = br.readLine().split(" ");
            int curVal = Integer.parseInt(params2[0]);
            int leftVal = Integer.parseInt(params2[1]);
            int rightVal = Integer.parseInt(params2[2]);
            TreeNode cur = map.getOrDefault(curVal,null);
            if(cur == null){
                cur = new TreeNode(curVal);
                map.put(curVal,cur);
            }
            if(leftVal != 0){
                cur.left = new TreeNode(leftVal);
                map.put(leftVal,cur.left);
            }
            if(rightVal != 0){
                cur.right = new TreeNode(rightVal);
                map.put(rightVal,cur.right);
            }
        }
        preOrder(head);
        System.out.println();
        inOrder(head);
        System.out.println();
        afterOrder(head);
    }
    
    /*
    先序遍历 用一个栈即可,因为栈是先入后厨,所以先压入左节点,在压入右节点,弹出的节点输出
    */
    public static void preOrder(TreeNode head){
        if(head != null){
            Stack<TreeNode> stack = new Stack<>();
            stack.push(head);
            while(!stack.isEmpty()){
                TreeNode cur = stack.pop();
                System.out.print(cur.val + " ");
                if (cur.right != null){
                    stack.push(cur.right);
                }
                if (cur.left != null){
                    stack.push(cur.left);
                }
            }
            
        }
    }
    
    //中序遍历 213
    //先把左边界全部进栈,弹出一个节点,其有右节点,则在压入他的所有左边界
    public static void inOrder(TreeNode head){
        if (head != null){
            Stack<TreeNode> stack = new Stack<>();
            while (!stack.isEmpty() || head !=null){
                if (head!=null){
                    stack.push(head);
                    head = head.left;
                }else {
                    //左树已经到头来,则可以pop了,然后pop时也可以观察有无右树
                    head = stack.pop();
                    System.out.print(head.val + " ");
                    head = head.right;
                }

            }
        }
    }
    
    //后序遍历231  --- 两个栈 第一个栈头左右 --》头右左 再用一个栈左右头
    public static void afterOrder(TreeNode head){
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        stack1.push(head);
        while(!stack1.isEmpty()){
            TreeNode cur = stack1.pop();
            if(cur.left != null){
                stack1.push(cur.left);
            }
            if(cur.right != null){
                stack1.push(cur.right);
            }
            stack2.push(cur);
        }
        while(!stack2.isEmpty()){
            System.out.print(stack2.pop().val + " ");
        }
    }
}


发表于 2022-03-01 14:53:55 回复(0)
import java.io.*;
import java.util.Scanner;
import java.util.Stack;
 class TreeNode{
        TreeNode left;
        TreeNode right;
        int val;
        public TreeNode(int val){
            this.val = val;
        }
    }
public class Main{
    public static TreeNode createTree(BufferedReader br) throws Exception{
        String[] str = br.readLine().split(" ");
        int[] node = new int[str.length];
        for(int i = 0; i < str.length; i++){
            node[i] = Integer.parseInt(str[i]);
        }
           //构造该行输入对应节点
        TreeNode root = new TreeNode(node[0]);
        if( node[1] != 0 )  root.left = createTree(br);
        if( node[2] != 0 )  root.right = createTree(br);
        return root;
    }
    
    public static void main(String[] args) throws Exception{
//         Scanner sc = new Scanner(System.in);
//         String str = sc.nextLine();
//         TreeNode root = createTree(sc);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        TreeNode root = createTree(br);
        
        preOrder2(root);
        System.out.println();    
        infixOrder2(root);
        System.out.println(); 
        postOrder2(root);
        System.out.println(); 
    }
    // 递归实现
    public static void preOrder(TreeNode root){       
        if(root == null){
          return; 
        } 
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }
        public static void infixOrder(TreeNode root){
        if(root == null){
          return; 
        }
        infixOrder(root.left);
        System.out.print(root.val+" ");  
        infixOrder(root.right);
    }
        public static void postOrder(TreeNode root){
         if(root == null){
          return; 
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");  
    }
    // 非递归实现
    //先压入头节点,再弹出它,压入他的右节点和左借点。重复
    public static void preOrder2(TreeNode root){
        Stack<TreeNode> st = new Stack();
        if(root == null){
            return;
        }
        st.push(root);
        while(!st.isEmpty()){
            root = st.pop();
            System.out.print(root.val+" ");
            if(root.right != null){
                st.push(root.right);
            }
            if(root.left != null){
                st.push(root.left);
            }
        }
    }
    public static void infixOrder2(TreeNode root){
        Stack<TreeNode> st = new Stack();
        if(root == null){
            return;
        }
        st.push(root);
        while(root.left != null){
            root = root.left;
            st.push(root);
        }
        while(!st.isEmpty()){
            root = st.pop();
            System.out.print(root.val+" ");
            if(root.right != null){
                root = root.right;
                st.push(root);
                while(root.left != null){
                    root = root.left;
                    st.push(root);
                }
            }
        }
    }
    public static void postOrder2(TreeNode root){
        Stack<TreeNode> st1 = new Stack();
        Stack<TreeNode> st2 = new Stack();
        // 先把shuju数据全压入s2
        if(root == null){
            return;
        }
        st1.push(root);
        while(!st1.isEmpty()){
            root = st1.pop();
            st2.push(root);
            if(root.left != null){
                st1.push(root.left);
            }
            if(root.right != null){
                st1.push(root.right);
            }
        }
        //依次弹出s2
        while(!st2.isEmpty()){
             root = st2.pop();
             System.out.print(root.val+" ");
        }
        
    }
}
发表于 2022-02-25 16:24:07 回复(0)
递归版遍历
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashMap;

class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // 构建二叉树
        String[] params = br.readLine().split(" ");
        int n = Integer.parseInt(params[0]);
        TreeNode root = new TreeNode(Integer.parseInt(params[1]));
        HashMap<Integer, TreeNode> map = new HashMap<>();
        map.put(root.val, root);
        for(int i = 0; i < n; i++){
            params = br.readLine().split(" ");
            int val = Integer.parseInt(params[0]);
            int leftVal = Integer.parseInt(params[1]);
            int rightVal = Integer.parseInt(params[2]);
            TreeNode node = map.get(val);
            if(leftVal != 0) {
                node.left = new TreeNode(leftVal);
                map.put(leftVal, node.left);
            }
            if(rightVal != 0) {
                node.right = new TreeNode(rightVal);
                map.put(rightVal, node.right);
            }
        }
        // 三种遍历
        preOrder(root);
        System.out.println();
        inOrder(root);
        System.out.println();
        postOrder(root);
    }
    
    private static void preOrder(TreeNode node) {
        if(node == null) return;
        System.out.print(node.val + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
    
    private static void inOrder(TreeNode node) {
        if(node == null) return;
        inOrder(node.left);
        System.out.print(node.val + " ");
        inOrder(node.right);
    }
    
    private static void postOrder(TreeNode node) {
        if(node == null) return;
        postOrder(node.left);
        postOrder(node.right);
        System.out.print(node.val + " ");
    }
}
迭代版遍历
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Stack;

class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // 构建二叉树
        String[] params = br.readLine().split(" ");
        int n = Integer.parseInt(params[0]);
        TreeNode root = new TreeNode(Integer.parseInt(params[1]));
        HashMap<Integer, TreeNode> map = new HashMap<>();
        map.put(root.val, root);
        for(int i = 0; i < n; i++){
            params = br.readLine().split(" ");
            int val = Integer.parseInt(params[0]);
            int leftVal = Integer.parseInt(params[1]);
            int rightVal = Integer.parseInt(params[2]);
            TreeNode node = map.get(val);
            if(leftVal != 0) {
                node.left = new TreeNode(leftVal);
                map.put(leftVal, node.left);
            }
            if(rightVal != 0) {
                node.right = new TreeNode(rightVal);
                map.put(rightVal, node.right);
            }
        }
        // 三种遍历
        preOrder(root);
        inOrder(root);
        postOrder(root);
    }
    
    private static void preOrder(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            System.out.print(node.val + " ");
            if(node.right != null) stack.push(node.right);
            if(node.left != null) stack.push(node.left);
        }
        System.out.println();
    }
    
    private static void inOrder(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        while(!stack.isEmpty() || root != null){
            // 先从左边走到头
            while(root != null) {
                stack.push(root);
                root = root.left;
            }
            // 然后右子树进行相同的操作
            if(!stack.isEmpty()){
                root = stack.pop();
                System.out.print(root.val + " ");
                root = root.right;
            }
        }
        System.out.println();
    }
    
    private static void postOrder(TreeNode root) {
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        stack1.push(root);
        while(!stack1.isEmpty()){
            TreeNode node = stack1.pop();
            stack2.push(node);
            if(node.left != null) stack1.push(node.left);
            if(node.right != null) stack1.push(node.right);
        }
        while(!stack2.isEmpty()) System.out.print(stack2.pop().val + " ");
        System.out.println();
    }
}

编辑于 2021-11-18 17:58:25 回复(4)
构建二叉树,然后递归。这个解法,时间堪忧,内存也不太好看。
时间花费 主要是 a,构建了二叉树
二叉树递归应该差别不大,即使用stack方式,O(N)。
如果想提高,感觉必须去掉后见二叉树的过程,直接读取数据的时候,就把信息保存起来,然后打印。


import java.util.Scanner;
import java.util.HashSet;

class Node{
    public int value;
    public Node left;
    public Node right;
    public Node(int val){
        this.value = val;
    }
}

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        if(sc.hasNextLine()){
            String[] input = sc.nextLine().split(" ");
            int n = Integer.parseInt(input[0]);
            Node root = new Node(Integer.parseInt(input[1]));
            HashSet<Node> set = new HashSet<Node>();
            set.add(root);
            
            for(int j= 0;j<n;j++){
                // build the binary tree
                String[] nodes = sc.nextLine().split(" ");
                int fatherValue = Integer.parseInt(nodes[0]);
                int leftValue = Integer.parseInt(nodes[1]);
                int rightValue = Integer.parseInt(nodes[2]);
                for(Node e:set){
                    if(e.value == fatherValue){
                        e.left = leftValue==0?null:new Node(leftValue);
                        e.right = rightValue==0?null:new Node(rightValue);
                        if(leftValue!=0){
                            set.add(e.left);
                        }
                        if(rightValue!=0){
                            set.add(e.right);
                        }
                        set.remove(e);
                        break;
                    }
                }
            }
            preOrder(root);
            System.out.print("\n");
            inOrder(root);
            System.out.print("\n");
            posOrder(root);
        }
    }
    
    public static void preOrder(Node d){
        if(d==null){
            return;
        }
        System.out.print(d.value);
        System.out.print(" ");
        if(d.left!=null){
            preOrder(d.left);
        }
        if(d.right!=null){
            preOrder(d.right);
        }
    }
    public static void inOrder(Node d){
        if(d==null){
            return;
        }
        if(d.left!=null){
            inOrder(d.left);
        }
        System.out.print(d.value);
        System.out.print(" ");
        
        if(d.right!=null){
            inOrder(d.right);
        }
    }
    public static void posOrder(Node d){
        if(d==null){
            return;
        }
        if(d.left!=null){
            posOrder(d.left);
        }
        if(d.right!=null){
            posOrder(d.right);
        }
        System.out.print(d.value);
        System.out.print(" ");
    }
    
}

发表于 2021-05-03 17:54:23 回复(0)

问题信息

上传者:小小
难度:
5条回答 4926浏览

热门推荐

通过挑战的用户

查看代码