简体   繁体   中英

Left or Right View of an Tree

What is the efficient code to provide the left/right view of an tree.

EX:-

                                1
                              /   \
     left view--->>          4     7                    <<--right view
                            / \   /
                           3   2  9
                                 /
                                8

The Left view for this Tree is- 1 4 3 8 and the right view is - 1 7 9 8

I have tried with level order traversal, But if the tree have some missing child's then it is difficult for me to find the starting point(in case of left view) or end point (in casse of right view) for the level, Please give suggestions

It is not difficult to get the left(or right) view using ONLY a single Queue. After enqueuing the rightmost child node, insert "null" in queue as a flag to mark the end of the next(child's) level while doing level-order traversal.

class Node{
    Node left, right;
    int value;
    Node(int value){
        left=right=null;
        this.value = value;
    }
}
public class BinaryTree
{
    Node root;
    public void leftView(){
        //Using single queue.
        boolean leftmost = true;
        if(this.root == null) return;
        Queue<Node> q = new LinkedList<>();
        q.add(this.root);
        q.add(null);
        while(q.isEmpty() == false){
            Node rear = q.poll();
            if(leftmost == true) {
                if(rear == null) break; 
                System.out.print(rear.value + " ");
                leftmost = false;
            }
            if(rear.left != null)  q.add(rear.left);
            if(rear.right != null) q.add(rear.right);
            if(q.peek() == null) {
                leftmost = true;
                q.poll();    //remove it from rear
                q.add(null); //add it at front.
            }
        }
        //OUTPUT : 12 10 25 50
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        BinaryTree bt = new BinaryTree();
        bt.root = new Node(12);
        bt.root.left = new Node(10);
        bt.root.right = new Node(30);
        bt.root.right.left = new Node(25);
        bt.root.right.left.left = new Node(50);
        bt.root.right.right = new Node(40);
        //          12
        //       /     \
        //     10       30
        //            /    \
        //          25      40 
        //         /
        //       50
        bt.leftView();
    }
}

You're right that, with a level-order traversal like

Queue<Node> queue = new ArrayDeque<Node>();
for (Node node = root; node != null; node = queue.poll()) {
    if (node.leftChild != null) queue.add(node.leftChild);
    if (node.rightChild != null) queue.add(node.rightChild);
}

it's difficult to know where one level ends and the next begins. This can be addressed by using two queues.

Queue<Node> currentLevel = new ArrayDeque<Node>();
if (root != null) currentLevel.add(root);
while (true) {
    Node node = currentLevel.poll();
    if (node == null) break;
    /* node is the leftmost on its level */
    Queue<Node> nextLevel = new ArrayDeque<Node>();
    do {
        if (node.leftChild != null) nextLevel.add(node.leftChild);
        if (node.rightChild != null) nextLevel.add(node.rightChild);
        node = currentLevel.poll();
    } while (node != null);
    currentLevel = nextLevel;
}

Algorithm for printing left view:

  1. Take a global variable maxLevel to keep track of maximum level covered so far.
  2. Now whenever we receive a level which is higher than maxLevel so far then we print the value of that node.
  3. We do it in pre order way so that left is printed before right if present.

Here is the final code:

class BinaryTree {

    class TreeNode {
        int data;
        TreeNode left;
        TreeNode right;

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

    private static int maxLevel = -1;

    public static leftView(TreeNode root) {
       left_view(root, 0);
    }

    private static void left_view(BTNode root, int level) {
       if (root == null)
           return;

       if (level > maxLevel) {
           System.out.println(root.data);
           maxLevel = level;
       }

       left_view(root.left, level + 1);
       left_view(root.right, level + 1);
   }

package com.Trees.sumit;

import java.util.LinkedList; import java.util.Queue;

public class LeftView {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    TreeNode root = createBinaryTree();
    Queue<TreeNode> queue = new LinkedList<>();
    System.out.println("Left View" );
    queue.add(root);
    while (!queue.isEmpty()) {

        System.out.println(queue.peek().data);

        int queueSize = queue.size();

        while (queueSize > 0) {

            TreeNode removedNode = queue.poll();


            if (removedNode.left != null)
                queue.add(removedNode.left);

            if (removedNode.right != null)
                queue.add(removedNode.right);



            queueSize--;
        }

    }

}

public static class TreeNode {

    int data;
    TreeNode left;
    TreeNode right;

    public TreeNode(int data) {
        super();
        this.data = data;
    }

}

private static TreeNode createBinaryTree() {
    // TODO Auto-generated method stub
    TreeNode rootNode = new TreeNode(40);
    TreeNode root20 = new TreeNode(20);
    TreeNode root10 = new TreeNode(10);
    TreeNode root30 = new TreeNode(30);
    TreeNode root50 = new TreeNode(50);
    TreeNode root55 = new TreeNode(55);
    TreeNode root57 = new TreeNode(57);

    TreeNode root60 = new TreeNode(60);
    TreeNode root70 = new TreeNode(70);

    rootNode.left = root20;
    rootNode.right = root60;

    root50.right = root55;
    root55.right = root57;

    root20.left = root10;
    root20.right = root30;

    root60.left = root50;
    root60.right = root70;

    return rootNode;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM