Print the path between two leaf nodes of a binary tree.

Source: Internet
Author: User

Print the path between two leaf nodes of a binary tree.
Reprinted please indicate the source: http://blog.csdn.net/luonanqin



Two days ago, I saw a campus recruitment interview question from Baidu on the Internet: output the path between two leaf nodes in the binary tree. It is not very difficult, so it took some time to implement it in Java. If you have better ideas, you can discuss them together. (Another interview question is to find the longest path in the binary tree, that is, the two leaf nodes with the farthest distance. I will not release it because of the implementation on the Internet .)


Public class TwoLeafPath {// temporarily store the two leaf nodes to be used public static Node2 leaf = null; // indicates that the leaf node public static boolean find = false has been found; // there is really no way to output a non-balanced non-Complete Binary Tree, so you can paint it yourself: Ppublic static Node2 generateTree () {Node2 root = new Node2 (1 ); node2 node2 = new Node2 (2); Node2 node3 = new Node2 (3); Node2 node4 = new Node2 (4); Node2 node5 = new Node2 (5 ); node2 node6 = new Node2 (6); Node2 node7 = new Node2 (7); Node2 node8 = new Node2 (8); Node2 node9 = new Node2 (9); Node2 node10 = new Node2 (10); Node2 node11 = new Node2 (11 ); node2 node12 = new Node2 (12); root. setParentNode (null); root. setLeftNode (node2); root. setRightNode (node3); shard (node4); node2.setRightNode (node5); shard (node6); shard (node7); node4.setRightNode (node8); node5.setRightNode (node9); shard (node10 ); node9.setLeftNode (node11 ); Node11.setRightNode (node12); return root;} // the fastest way to find the leaf node public static void findNode (Node2 root, int data) in the future sequential Traversal) {// if the leaf node is found, stop traversing if (! Find) {if (root. getLeftNode ()! = Null) {root. getLeftNode (). setParentNode (root); findNode (root. getLeftNode (), data) ;}// if the leaf node is found, stop traversing if (! Find) {if (root. getRightNode ()! = Null) {root. getRightNode (). setParentNode (root); findNode (root. getRightNode (), data) ;}} if (root. getData () = data) {leaf = root; find = true; return;} else {return;} public static void printLeavesPath (Node2 leaf1, Node2 leaf2) {int leaf1Data = leaf1.getData (); int leaf2Data = leaf2.getData (); Deque <Integer> leaf1Path = new queue list <Integer> (); deque <Integer> leaf2Path = new shortlist <Integer> (); while (True) {leaf1Path. offerFirst (leaf1.getData (); leaf1 = leaf1.getParentNode (); if (leaf1 = null) {break;} System. out. println ("Leaf" + leaf1Data + "Path:" + leaf1Path); while (true) {leaf2Path. offerFirst (leaf2.getData (); leaf2 = leaf2.getParentNode (); if (leaf2 = null) {break;} System. out. println ("Leaf" + leaf2Data + "Path:" + leaf2Path); int temp = 0; // compare the paths of the two Leaf nodes. Start searching from the root node. If different nodes are found, the two paths are split from the current node. You can output the path while (leaf1Path. peekFirst () = leaf2Path. peekFirst () {temp = leaf1Path. pollFirst (); leaf2Path. pollFirst ();} // sequential output Iterator <Integer> leaf1Iter = leaf1Path. iterator (); // output Iterator in reverse order <Integer> leaf2Iter = leaf2Path. descendingIterator (); StringBuffer result = new StringBuffer (); while (leaf2Iter. hasNext () {result. append (leaf2Iter. next () + ",");} result. append (temp + ","); while (leaf1Iter. hasNext () {result. append (leaf1Iter. next () + ",");} System. out. println ("Leaf" + leaf1Data + "& Leaf" + leaf2Data + "Path:" + result. substring (0, result. length ()-2);} public static void main (String [] args) {Node2 root = generateTree (); int data1 = 6; int data2 = 12; findNode (root, data1); find = false; Node2 leaf1 = leaf; findNode (root, data2); find = false; Node2 leaf2 = leaf; if (leaf1 = null) {System. out. println ("Can't find leaf with" + data1);} if (leaf2 = null) {System. out. println ("Can't find leaf with" + data2);} printLeavesPath (leaf1, leaf2 );}}

The key code above, the rest of the code can be self-developed, or refer to my github: https://github.com/luonanqin/study/tree/master/Algorithm/src


Traverse all the paths from the root to the leaf node in a binary tree in the middle order

Why must we use the central order ?? I think the efficiency of the First Order is higher. Of course, if the middle order is used, replace the order of the statements in the following recursive function.
Thought: Is the current node? --> NO: determines the left and right subtree. If the current node or left and right subtree is: inserts the current node into the linked list.
(Write only the function implementation part)

Struct BTree
{
Int node;
BTree * pLeft;
BTree * pRight;
};

Struct List // The purpose of this linked List is to record the path node, so that the called function can be processed through a linked List header pointer. You can directly cout
{
Int node;
List * pNext;
};

Bool IsPath (BTree * pRoot, List ** pHead, int leaf)
{
List * pInsert = NULL;

If (pRoot-> node = leaf)
{
* PHead = new List;
* PHead-> node = leaf;
* PHead-> pNext = NULL;

// Record the node
Cout <"->" <leaf;

Return true;
}

If (pRoot-> pLeft)
{
If (IsPath (pRoot-> pLeft, pHead, leaf ))
{
PInsert = new List;
PInsert-> node = pRoot-> node;
PInsert-> pNext = * pHead;
* PHead = pInsert;

// Record the node
Cout <"->" <leaf;

Return true;
}
}

If (pRoot-> pRight)
{
If (IsPath (pRoot-> pRight, pHead, leaf ))
{
PInsert = new List;
PInsert-> node = pRoot-> node;
PInsert-> pNext = * pHead;
* PHead = pInsert;

// Record the node
Cout <"->" <leaf;

Return true;
}
}

Return false;
}

Call this function:
Set the root node to pTree, the head pointer of the linked list to pHead = NULL, and the leaf node to 5,
Call:
IsPath (pTree, & pHead, 5 );
If (pHead = NULL)
{
; // No such leaf node
}... Remaining full text>
 
Binary Tree leaf node

The leaf node has no children at the end!
To solve this problem, you need to know that in any binary tree, the number of nodes with a degree of zero is a, and the number of nodes with a degree of 2 is B, then a = B + 1.
In this question, B = 18, a = 19,
The answer to this question is: B * 2 + a = 18*2 + 19
(I'm not happy with it.) (B * 2 means that two leaf nodes have degrees of 2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.