链表和树

一、链表

输入一个链表,从尾到头打印链表每个节点的值。

入栈,出栈。完整代码实现如下

import java.util.Stack;


import java.util.ArrayList;

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
 @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}

//题方法一:比较容易理解
 class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }

        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        return list;
    }
}

public class 从尾到头打印链表的值 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        System.out.println(node1);
        System.out.println(new Solution().printListFromTailToHead(node1));
    }
}


基于此,进行优化。

1、用两个列表实现。顺序存入一个列表,逆序遍历列表

    public static ArrayList<Integer> printListFromTailToHead1(ListNode listNode) {
        //先存入list
        ArrayList<Integer> list1 = new ArrayList<>();
        while (listNode != null) {
            list1.add(listNode.val);
            listNode = listNode.next;
        }
        //再逆序存入另一个list
        ArrayList<Integer> list2 = new ArrayList<>();
        for (int i = list1.size() - 1; i >= 0; i--) {
            list2.add(list1.get(i));
        }
        return list2;
    }

2、用一个列表实现。思路同上,输出时在一个list中完成对称翻转

    public static ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
        //先存入list
        ArrayList<Integer> list = new ArrayList<>();
        while (listNode != null) {
            list.add(listNode.val);
            listNode = listNode.next;
        }
        //同一list中元素逆序
        int midIndex = list.size() / 2 - 1;
        int totalSize = list.size();
        for (int i = 0; i <= midIndex; i++) {
            int tmp = list.get(i);
            list.set(i, list.get(totalSize - 1 - i));
            list.set(totalSize - 1 - i, tmp);
        }
        return list;
    }

3、用递归实现

    public static ArrayList<Integer> printListFromTailToHead3(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        add2List(list, listNode);
        return list;
    }

    private static void add2List(ArrayList<Integer> list, ListNode listNode) {
//        System.out.println(list); list在递归中始终为空
        if (listNode != null) {
            add2List(list, listNode.next);
            list.add(listNode.val);
        }
    }

二、二叉树

public class BinaryTree {

    int data; // 根节点数据
    BinaryTree left; // 左子树
    BinaryTree right; // 右子树

    public BinaryTree(int data) // 实例化二叉树类
    {
        this.data = data;
        left = null;
        right = null;
    }

    public void insert(BinaryTree root, int data) { // 向二叉树中插入子节点
        if (data > root.data) // 二叉树的左节点都比根节点小
        {
            if (root.right == null) {
                root.right = new BinaryTree(data);
            } else {
                this.insert(root.right, data);
            }
        } else { // 二叉树的右节点都比根节点大
            if (root.left == null) {
                root.left = new BinaryTree(data);
            } else {
                this.insert(root.left, data);
            }
        }
    }

    // 当建立好二叉树类后可以创建二叉树实例,并实现二叉树的先根遍历,中根遍历,后根遍历,代码如下:

    public static void preOrder(BinaryTree root) { // 先根遍历
        if (root == null)
            return;
        System.out.print(root.data + "-");// 代表根
        preOrder(root.left);
        preOrder(root.right);

    }

    public static void inOrder(BinaryTree root) { // 中根遍历

        if (root == null)
            return;
        inOrder(root.left);
        System.out.print(root.data + "--");
        inOrder(root.right);

    }

    public static void postOrder(BinaryTree root) { // 后根遍历

        if (root == null)
            return;
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.data + "---");

    }

    public static void main(String[] str) {
        int[] array = { 12, 76, 35, 22, 16, 48, 90, 46, 9, 40 };
        BinaryTree root = new BinaryTree(array[0]); // 创建二叉树
        for (int i = 1; i < array.length; i++) {
            root.insert(root, array[i]); // 向二叉树中插入数据
        }
        System.out.println("先根遍历:");
        preOrder(root);
        System.out.println();
        System.out.println("中根遍历:");
        inOrder(root);
        System.out.println();
        System.out.println("后根遍历:");
        postOrder(root);
    }
}




/* * 基于链表实现结构 */ package dsa; public class TreeLinkedList implements Tree { private Object element;//根节点 private TreeLinkedList parent, firstChild, nextSibling;//父亲、长子及最大的弟弟 //(单节点)构造方法 public TreeLinkedList() { this(null, null, null, null); } //构造方法 public TreeLinkedList(Object e, TreeLinkedList p, TreeLinkedList c, TreeLinkedList s) { element = e; parent = p; firstChild = c; nextSibling = s; } /*---------- Tree接口中各方法的实现 ----------*/ //返回当前节点中存放的对象 public Object getElem() { return element; } //将对象obj存入当前节点,并返回此前的内容 public Object setElem(Object obj) { Object bak = element; element = obj; return bak; } //返回当前节点的父节点;对于根节点,返回null public TreeLinkedList getParent() { return parent; } //返回当前节点的长子;若没有孩子,则返回null public TreeLinkedList getFirstChild() { return firstChild; } //返回当前节点的最大弟弟;若没有弟弟,则返回null public TreeLinkedList getNextSibling() { return nextSibling; } //返回当前节点后代元素的数目,即以当前节点为根的子的规模 public int getSize() { int size = 1;//当前节点也是自己的后代 TreeLinkedList subtree = firstChild;//从长子开始 while (null != subtree) {//依次 size += subtree.getSize();//累加 subtree = subtree.getNextSibling();//所有孩子的后代数目 } return size;//即可得到当前节点的后代总数 } //返回当前节点的高度 public int getHeight() { int height = -1; TreeLinkedList subtree = firstChild;//从长子开始 while (null != subtree) {//依次 height = Math.max(height, subtree.getHeight());//在所有孩子中取最大高度 subtree = subtree.getNextSibling(); } return height+1;//即可得到当前节点的高度 } //返回当前节点的深度 public int getDepth() { int depth = 0; TreeLinkedList p = parent;//从父亲开始 while (null != p) {//依次 depth++; p = p.getParent();//访问各个真祖先 } return depth;//真祖先的数目,即为当前节点的深度 } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值