原文:
给定一棵二叉树,不使用递归打印其所有根到叶路径。例如,考虑下面的二叉树。
6
/ \
3 5
/ \ \
2 5 4
/ \
7 4
there are 4 leaves, hence 4 root to leaf paths -
6->3->2
6->3->5->7
6->3->5->4
6->5>4
我们强烈建议你尽量减少浏览器,先自己试试这个。 我们可以迭代遍历树(我们已经使用了)。问题是,如何扩展遍历来打印根到叶的路径?其思想是维护一个映射来存储二叉树节点的父指针。现在,每当我们在进行迭代前序遍历时遇到一个叶节点,我们就可以使用父指针轻松地打印根到叶路径。下面是这个想法的实现。
c
// c program to print root to leaf path without
// using recursion
#include
using namespace std;
/* a binary tree */
struct node
{
int data;
struct node *left, *right;
};
/* helper function that allocates a new node
with the given data and null left and right
pointers.*/
node* newnode(int data)
{
node* node = new node;
node->data = data;
node->left = node->right = null;
return node;
}
/* function to print root to leaf path for a leaf
using parent nodes stored in map */
void printtoptobottompath(node* curr,
map parent)
{
stack stk;
// start from leaf node and keep on pushing
// nodes into stack till root node is reached
while (curr)
{
stk.push(curr);
curr = parent[curr];
}
// start popping nodes from stack and print them
while (!stk.empty())
{
curr = stk.top();
stk.pop();
cout << curr->data << " ";
}
cout << endl;
}
/* an iterative function to do preorder traversal
of binary tree and print root to leaf path
without using recursion */
void printroottoleaf(node* root)
{
// corner case
if (root == null)
return;
// create an empty stack and push root to it
stack nodestack;
nodestack.push(root);
// create a map to store parent pointers of binary
// tree nodes
map parent;
// parent of root is null
parent[root] = null;
/* pop all items one by one. do following for
every popped item
a) push its right child and set its parent
pointer
b) push its left child and set its parent
pointer
note that right child is pushed first so that
left is processed first */
while (!nodestack.empty())
{
// pop the top item from stack
node* current = nodestack.top();
nodestack.pop();
// if leaf node encountered, print top to
// bottom path
if (!(current->left) && !(current->right))
printtoptobottompath(current, parent);
// push right & left children of the popped node
// to stack. also set their parent pointer in
// the map
if (current->right)
{
parent[current->right] = current;
nodestack.push(current->right);
}
if (current->left)
{
parent[current->left] = current;
nodestack.push(current->left);
}
}
}
// driver program to test above functions
int main()
{
/* constructed binary tree is
10
/ \
8 2
/ \ /
3 5 2 */
node* root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->left->right = newnode(5);
root->right->left = newnode(2);
printroottoleaf(root);
return 0;
}
java 语言(一种计算机语言,尤用于创建网站)
// java program to print root to leaf path without
// using recursion
import java.util.stack;
import java.util.hashmap;
public class printpath {
/* function to print root to leaf path for a leaf
using parent nodes stored in map */
public static void printtoptobottompath(node curr, hashmap parent)
{
stack stk=new stack<>() ;
// start from leaf node and keep on pushing
// nodes into stack till root node is reached
while (curr!=null)
{
stk.push(curr);
curr = parent.get(curr);
}
// start popping nodes from stack and print them
while (!stk.isempty())
{
curr = stk.pop();
system.out.print(curr.data " ");
}
system.out.println();
}
/* an iterative function to do preorder traversal
of binary tree and print root to leaf path
without using recursion */
public static void printroottoleaf(node root)
{
// corner case
if (root == null)
return;
// create an empty stack and push root to it
stack nodestack=new stack<>();
nodestack.push(root);
// create a map to store parent pointers of binary
// tree nodes
hashmap parent=new hashmap<>();
// parent of root is null
parent.put(root,null);
/* pop all items one by one. do following for
every popped item
a) push its right child and set its parent
pointer
b) push its left child and set its parent
pointer
note that right child is pushed first so that
left is processed first */
while (!nodestack.isempty())
{
// pop the top item from stack
node current = nodestack.pop();
// if leaf node encountered, print top to
// bottom path
if (current.left==null && current.right==null)
printtoptobottompath(current, parent);
// push right & left children of the popped node
// to stack. also set their parent pointer in
// the map
if (current.right!=null)
{
parent.put(current.right,current);
nodestack.push(current.right);
}
if (current.left!=null)
{
parent.put(current.left,current);
nodestack.push(current.left);
}
}
}
public static void main(string args[]) {
node root=new node(10);
root.left = new node(8);
root.right = new node(2);
root.left.left = new node(3);
root.left.right = new node(5);
root.right.left = new node(2);
printroottoleaf(root);
}
}
/* a binary tree node */
class node
{
int data;
node left, right;
node(int data)
{
left=right=null;
this.data=data;
}
};
//this code is contributed by gaurav tiwari
python 3
# python3 program to print root to
# leaf path without using recursion
# helper function that allocates a new
# node with the given data and none left
# and right pointers.
class newnode:
def __init__(self, data):
self.data = data
self.left = self.right = none
# function to print root to leaf path for a
# leaf using parent nodes stored in map
def printtoptobottompath(curr, parent):
stk = []
# start from leaf node and keep on appending
# nodes into stack till root node is reached
while (curr):
stk.append(curr)
curr = parent[curr]
# start popping nodes from stack
# and print them
while len(stk) != 0:
curr = stk[-1]
stk.pop(-1)
print(curr.data, end = " ")
print()
# an iterative function to do preorder
# traversal of binary tree and print
# root to leaf path without using recursion
def printroottoleaf(root):
# corner case
if (root == none):
return
# create an empty stack and
# append root to it
nodestack = []
nodestack.append(root)
# create a map to store parent
# pointers of binary tree nodes
parent = {}
# parent of root is none
parent[root] = none
# pop all items one by one. do following
# for every popped item
# a) append its right child and set its
# parent pointer
# b) append its left child and set its
# parent pointer
# note that right child is appended first
# so that left is processed first
while len(nodestack) != 0:
# pop the top item from stack
current = nodestack[-1]
nodestack.pop(-1)
# if leaf node encountered, print
# top to bottom path
if (not (current.left) and
not (current.right)):
printtoptobottompath(current, parent)
# append right & left children of the
# popped node to stack. also set their
# parent pointer in the map
if (current.right):
parent[current.right] = current
nodestack.append(current.right)
if (current.left):
parent[current.left] = current
nodestack.append(current.left)
# driver code
if __name__ == '__main__':
# constructed binary tree is
# 10
# / \
# 8 2
# / \ /
# 3 5 2
root = newnode(10)
root.left = newnode(8)
root.right = newnode(2)
root.left.left = newnode(3)
root.left.right = newnode(5)
root.right.left = newnode(2)
printroottoleaf(root)
# this code is contributed by pranchalk
c
// c# program to print root to leaf path without
// using recursion
using system;
using system.collections.generic;
public class printpath
{
/* function to print root to leaf path for a leaf
using parent nodes stored in map */
public static void printtoptobottompath(node curr,
dictionary parent)
{
stack stk = new stack() ;
// start from leaf node and keep on pushing
// nodes into stack till root node is reached
while (curr != null)
{
stk.push(curr);
curr = parent[curr];
}
// start popping nodes from stack and print them
while (stk.count != 0)
{
curr = stk.pop();
console.write(curr.data " ");
}
console.writeline();
}
/* an iterative function to do preorder traversal
of binary tree and print root to leaf path
without using recursion */
public static void printroottoleaf(node root)
{
// corner case
if (root == null)
return;
// create an empty stack and push root to it
stack nodestack = new stack();
nodestack.push(root);
// create a map to store parent
// pointers of binary tree nodes
dictionary parent = new dictionary();
// parent of root is null
parent.add(root, null);
/* pop all items one by one. do following for
every popped item
a) push its right child and set its parent
pointer
b) push its left child and set its parent
pointer
note that right child is pushed first so that
left is processed first */
while (nodestack.count != 0)
{
// pop the top item from stack
node current = nodestack.pop();
// if leaf node encountered, print top to
// bottom path
if (current.left == null && current.right == null)
printtoptobottompath(current, parent);
// push right & left children of the popped node
// to stack. also set their parent pointer in
// the map
if (current.right != null)
{
parent.add(current.right,current);
nodestack.push(current.right);
}
if (current.left != null)
{
parent.add(current.left,current);
nodestack.push(current.left);
}
}
}
// driver code
public static void main(string []args)
{
node root = new node(10);
root.left = new node(8);
root.right = new node(2);
root.left.left = new node(3);
root.left.right = new node(5);
root.right.left = new node(2);
printroottoleaf(root);
}
}
/* a binary tree node */
public class node
{
public int data;
public node left, right;
public node(int data)
{
left = right = null;
this.data = data;
}
};
// this code is contributed rajput-ji
java 描述语言
输出:
10 8 3
10 8 5
10 2 2
本文由阿迪蒂亚·戈尔供稿。如果你发现任何不正确的地方,请写评论,或者你想分享更多关于上面讨论的话题的信息
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处