輸出單層節點

題目

對於一棵二叉樹,請設計一個算法,創建含有某一深度上所有結點的鏈表。
給定二叉樹的根結點指針TreeNode* root,以及鏈表上結點的深度,請返回一個鏈表ListNode,代表該深度上所有結點的值,請按樹上從左往右的順序鏈接,保證深度不超過樹的高度,樹上結點的值爲非負整數且不超過100000。

實現

public class TreeLevel {
    public Node getTreeLevel(BinaryTreeNode root, int dep) {
        if(root==null || dep<1){
            return null;
        }
        Queue<BinaryTreeNode> queue = new ArrayDeque<BinaryTreeNode>();
        queue.add(root);
        while (!queue.isEmpty() && dep>1){
            int len = queue.size();
            for(int i=0;i<len;i++){
                BinaryTreeNode temp = queue.poll();
                if(temp.left!=null){
                    queue.add(temp.left);
                }
                if(temp.right!=null){
                    queue.add(temp.right);
                }
            }
            dep--;
        }

        Node head = new Node(queue.poll().value);
        Node temp = head;
        while (!queue.isEmpty()){
            temp.next = new Node(queue.poll().value);
            temp=temp.next;
        }
        return head;
    }

public Node getTreeLevel2(BinaryTreeNode root, int dep) {
        if(root==null || dep<1){
            return null;
        }
        Queue<BinaryTreeNode> queue = new ArrayDeque<BinaryTreeNode>();
        queue.add(root);
        int current_dep =1;
        int current_num =1;
        int next_num =0;
        BinaryTreeNode current_node = null;
        while (!queue.isEmpty()){
            if(current_dep==dep){
                break;
            }
            current_node = queue.poll();
            current_num--;
            if(current_node.left!=null){
                queue.add(current_node.left);
                next_num++;
            }
            if(current_node.right!=null){
                queue.add(current_node.right);
                next_num++;
            }
            if(current_num==0){
                current_num = next_num;
                next_num=0;
                current_dep++;
            }

        }

        Node head = new Node(queue.poll().value);
        Node temp = head;
        while (!queue.isEmpty()){
            temp.next = new Node(queue.poll().value);
            temp=temp.next;
        }
        return head;
    }
}


class Node {
    int value;
    Node next;
    public Node(int value){
        this.value=value;
    }
    public Node(){

    }
}

class BinaryTreeNode {
    int value;
    BinaryTreeNode left;
    BinaryTreeNode right;
    public BinaryTreeNode() {
    }

    public BinaryTreeNode(int val) {
        this.value = val;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章