二叉樹的構建(非常簡便)

自己研究的一種創建樹比較簡便且容易理解的方法,平時刷題如果需要創建樹,該方法也是很快捷的。

import java.util.*;

class TreeNode {
    int val;
    TreeNode left = null;
    TreeNode right = null;

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

public class Test {

    /**
     *           1
     *       2      3
     *    4   #   5   6
     *  7  8 # # # # # #
     * 9
     *
     *           1
     *       1      1
     *     1   #   #   1
     *   #  1 # # # # #  1
     */
    private String[] treeValue = {
            "1",
            "1", "1",
            "1", "#", "#", "1",
            "#", "1", "#", "#", "#", "#", "#", "1"
    };
    
	// 層序遍歷思路
    public TreeNode buildTree() {
        LinkedList<TreeNode> queue = new LinkedList<>();
        TreeNode head = new TreeNode(Integer.parseInt(treeValue[0]));
        queue.offer(head);
        for(int i = 1; i <= treeValue.length; i = i + 2) {
            TreeNode node = queue.poll();
            if(node == null) {
                continue;
            }
            if(i < treeValue.length && !"#".equals(treeValue[i])) {
                node.left = new TreeNode(Integer.parseInt(treeValue[i]));
                queue.offer(node.left);
            } else {
                queue.offer(null);
            }
            if(i + 1 < treeValue.length && !"#".equals(treeValue[i + 1])) {
                node.right = new TreeNode(Integer.parseInt(treeValue[i + 1]));
                queue.offer(node.right);
            } else {
                queue.offer(null);
            }

        }
        return head;
    }

    public static void main(String[] args) {
        Test test = new Test();
        TreeNode head = test.buildTree();

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章