二叉樹節點的層級輸出

更詳細的講解和代碼調試演示過程,請參看視頻
如何進入google,算法面試技能全面提高指南java


二叉樹節點的變量有三種方法,分別是前序遍歷,中序遍歷,後續遍歷。如今,要求咱們實現算法,使得逐層將節點打印出來,例如開始先打印最高層,也就是節點5,而後打印第二層,也就是節點3, 7, 接着打印第三層,也便是節點1,4,6,8;最後打印最底層,也就是節點0, 2, 9.node

這個問題處理不難,咱們依賴隊列這個數據結構可方便實現這個功能。作法是,面試

1,  首先把根節點加入隊列:算法

5微信

2, 接着把隊列頭結點的數值打印出來,把頭結點的左右孩子加入隊列markdown

5->3->7數據結構

3,   去掉隊列頭結點,而後進入步驟2.app

根據上面步驟,算法對節點的處理以下
list: 5
output: 5函數

list: 3->7
output: 3post

list: 7->1->4
output: 7

list: 1->4->6->8
output: 1

list: 4->6->8->0->2
output: 4

list: 6->8->0->2
output: 6

list: 8->0->2
output: 8

list: 0->2->9
output: 0

list: 2->9
output: 2

list: 9
output: 9

對應的代碼實現以下:

public class ListUtility {
    private Node tail;
    private Node head;
    private int listLen = 0;
    private int postingListLen = 0;
    HashMap<Integer, PostingNode> map = new HashMap<Integer, PostingNode>();
    TreeNode treeHead = null;

    public TreeNode createTree() {
        int[] a = new int[]{5,7,3,1,2,6,8,4,9,0};
        for (int i = 0; i < 10; i++) {
            insertTreeNode(a[i]);
        }

        return treeHead;
    }

    private void insertTreeNode(int val) {
        if (treeHead == null) {
            treeHead = new TreeNode();
            treeHead.val = val;
            treeHead.left = treeHead.right = null;
            return;
        }

        TreeNode node = treeHead;
        while (node != null) {
            if (node.val > val && node.left  != null) {
                node = node.left;
                continue;
            }

            if (node.val <= val && node.right != null) {
                node = node.right;
                continue;
            }

            TreeNode temp = new TreeNode();
            temp.val = val;
            temp.left = null;
            temp.right = null;

            if (node.val > val) {
                node.left = temp;
                break;
            } else {
                node.right = temp;
                break;
            }
        }
    }
...
}

在ListUtility中,經過createTree和insertTreeNode兩個函數來構造排序二叉樹。createTree會返回樹的根節點。

層級打印的邏輯實如今類PrintTreeList:

import java.util.ArrayList;

public class PrintTreeList {
    private ArrayList<TreeNode> list = new ArrayList<TreeNode>();

    public PrintTreeList(TreeNode head) {
        if (head != null) {
            list.add(head);        
        }
    }

    public void printTree() {

        while (list.size() > 0) {
            TreeNode t = list.remove(0);
            System.out.print(t.val + " ");
            if (t.left != null) {
                list.add(t.left);
            }

            if (t.right != null) {
                list.add(t.right);
            }
        }
    }
}

它的作法正是將樹節點依次加入隊列,而後去除隊列頭的節點打印出來,同時把當前節點的左右子節點加入隊列末尾。

因爲算法須要遍歷一次因此節點所以時間複雜度是O(n), 又由於須要爲每一個樹節點分配一個隊列節點,所以空間複雜度是O(n).更詳細的代碼講解和調試演示請參看視頻。

本文分享自微信公衆號 - Coding迪斯尼(gh_c9f933e7765d)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索