Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 二叉树中距离为k的节点_Algorithm_Data Structures - Fatal编程技术网

Algorithm 二叉树中距离为k的节点

Algorithm 二叉树中距离为k的节点,algorithm,data-structures,Algorithm,Data Structures,您将获得一个函数printKDistanceNodes,该函数包含二叉树的根节点、起始节点和整数K。完成该函数以按排序顺序打印距离给定起始节点K的所有节点(每行一个)的值。距离可以向上或向下。距离K处最多有一个节点向上-只需从起始节点开始,沿父节点向上移动K步。将其添加到已排序的数据结构中 然后需要添加向下的节点。为此,您可以使用队列执行BFS,在队列中插入节点时,将深度与节点一起存储(起始节点位于级别0,其子节点位于级别1,依此类推)。然后,当您弹出节点时,如果节点处于级别K,则将其添加到已排

您将获得一个函数printKDistanceNodes,该函数包含二叉树的根节点、起始节点和整数K。完成该函数以按排序顺序打印距离给定起始节点K的所有节点(每行一个)的值。距离可以向上或向下。

距离K处最多有一个节点向上-只需从起始节点开始,沿父节点向上移动K步。将其添加到已排序的数据结构中

然后需要添加向下的节点。为此,您可以使用队列执行BFS,在队列中插入节点时,将深度与节点一起存储(起始节点位于级别0,其子节点位于级别1,依此类推)。然后,当您弹出节点时,如果节点处于级别K,则将其添加到已排序的数据结构中。当您在K+1级别开始弹出节点时,可以停止

最后打印排序数据结构中的节点(它们将被排序)

编辑:如果没有父指针:

编写一个递归函数
intgo(Node Node)
,该函数返回相对于传入节点的起始节点的深度,如果节点的子树不包含start,则返回-1。该函数将发现第K个父项作为副作用。伪代码:

static Node KthParent = null;
static Node start = ...;
static int K = ...;

int Go(Node node) {
    if (node == start) return 0;

    intDepth = -1;

    if(node.LeftChild != null) {
        int leftDepth = Go(node.LeftChild);
        if(leftDepth >= 0) intDepth = leftDepth+1;
    }
    if (intDepth < 0 && node.rightChild != null) {
        int rightDepth = Go(node.RightChild);
        if(rightDepth >= 0) intDepth = rightDepth+1;
    }

    if(intDepth == K) KthParent = node;

    return intDepth;
}
静态节点KthParent=null;
静态节点开始=。。。;
静态int K=。。。;
int Go(节点){
if(node==start)返回0;
intDepth=-1;
if(node.LeftChild!=null){
int leftDepth=Go(node.LeftChild);
如果(leftDepth>=0)intDepth=leftDepth+1;
}
if(intDepth<0&&node.rightChild!=null){
int rightDepth=Go(node.RightChild);
如果(rightDepth>=0)intDepth=rightDepth+1;
}
如果(intDepth==K)KthParent=node;
返回深度;
}
private void printNodeAtN(节点根、节点开始、int k){
if(root!=null){
//计算起点是在左子树中还是在右子树中-如果起点是
//root此变量为null
布尔左=isLeft(根,开始);
int depth=深度(根,起始,0);
如果(深度==-1)
返回;
printNodeDown(根,k);
如果(根==开始)
返回;
如果(左){
如果(深度>k){
//打印左树中深度k级别的节点
printNode(深度-k-1,根.左);
}否则如果(深度k){
//打印左树中深度k级别的节点
printNode(depth-k-1,root.right);
}否则如果(深度右)
左转;
其他的
返还权;
}
}
调用方函数:
printkdistanceNode(根,n,k)

输出将打印距离给定节点上下k处的所有节点。

struct node{
struct node{
       int data;
       node* left;
       node* right;
       bool printed;
};

void print_k_dist(node** root,node** p,int k,int kmax);
void reinit_printed(node **root);


void print_k_dist(node** root,node **p,int k,int kmax)
{
     if(*p==NULL) return;
     node* par=parent(root,p);
     if(k<=kmax &&(*p)->printed==0)
     {
             cout<<(*p)->data<<" ";
             (*p)->printed=1;
             k++;
             print_k_dist(root,&par,k,kmax);
             print_k_dist(root,&(*p)->left,k,kmax);
             print_k_dist(root,&(*p)->right,k,kmax);
     }
     else
         return;
}



void reinit_printed(node **root)
{
     if(*root==NULL) return;
     else
     {
         (*root)->printed=0;
         reinit_printed(&(*root)->left);
         reinit_printed(&(*root)->right);
     }
}          
int数据; 节点*左; 节点*右; 布尔印刷; }; 无效打印区(节点**根,节点**p,int k,int kmax); 无效重新打印(节点**根); 无效打印区(节点**根,节点**p,整数k,整数kmax) { 如果(*p==NULL)返回; 节点*par=父节点(根,p); 如果(kprinted==0) { 库特里赫特,k,kmax); } 其他的 返回; } 无效重新打印(节点**根) { if(*root==NULL)返回; 其他的 { (*根)->打印=0; 重新打印(&(*根)->左); reinit_打印(&(*根)->右); } }
在此代码中,PrintNodesAtKDistance将首先尝试查找所需的节点

if(root.value == requiredNode)
当我们找到所需的节点时,我们将打印距离该节点K处的所有子节点

现在我们的任务是打印其他分支中的所有节点(转到并打印)。我们返回-1,直到找不到所需的节点。当我们得到所需的节点时,我们得到
lPath
rPath>=0
。现在我们必须打印距离
(lPath/rPath)-1

public void PrintNodes(Node Root, int requiredNode, int iDistance)

    {
        PrintNodesAtKDistance(Root, requiredNode, iDistance);
    }

    public int PrintNodesAtKDistance(Node root, int requiredNode, int iDistance)
    {
        if ((root == null) || (iDistance < 0))
            return -1;

        int lPath = -1, rPath = -1;

        if(root.value == requiredNode)
        {
            PrintChildNodes(root, iDistance);
            return iDistance - 1;
        }

        lPath = PrintNodesAtKDistance(root.left, requiredNode, iDistance);
        rPath = PrintNodesAtKDistance(root.right, requiredNode, iDistance);

        if (lPath > 0)
        {
            PrintChildNodes(root.right, lPath - 1);
            return lPath - 1;
        }
        else if(lPath == 0)
        {
            Debug.WriteLine(root.value);
        }

        if(rPath > 0)
        {
            PrintChildNodes(root.left, rPath - 1);
            return rPath - 1;
        }
        else if (rPath == 0)
        {
            Debug.WriteLine(root.value);
        }

        return -1;
    }

    public void PrintChildNodes(Node aNode, int iDistance)
    {
        if (aNode == null)
            return;

        if(iDistance == 0)
        {
            Debug.WriteLine(aNode.value);
        }

        PrintChildNodes(aNode.left, iDistance - 1);
        PrintChildNodes(aNode.right, iDistance - 1);
    }
public void打印节点(节点根、int requiredNode、int iDistance)
{
PrintNodesAtKDistance(根、requiredNode、iDistance);
}
公共int-PrintNodesAtKDistance(节点根、int-requiredNode、int-iDistance)
{
if((root==null)| |(iDistance<0))
返回-1;
intlpath=-1,rPath=-1;
if(root.value==requiredNode)
{
PrintChildNodes(根,iDistance);
返回状态-1;
}
lPath=PrintNodesAtKDistance(root.left,requiredNode,iDistance);
rPath=PrintNodesAtKDistance(root.right,requiredNode,iDistance);
如果(lPath>0)
{
PrintChildNodes(root.right,lPath-1);
struct node{
       int data;
       node* left;
       node* right;
       bool printed;
};

void print_k_dist(node** root,node** p,int k,int kmax);
void reinit_printed(node **root);


void print_k_dist(node** root,node **p,int k,int kmax)
{
     if(*p==NULL) return;
     node* par=parent(root,p);
     if(k<=kmax &&(*p)->printed==0)
     {
             cout<<(*p)->data<<" ";
             (*p)->printed=1;
             k++;
             print_k_dist(root,&par,k,kmax);
             print_k_dist(root,&(*p)->left,k,kmax);
             print_k_dist(root,&(*p)->right,k,kmax);
     }
     else
         return;
}



void reinit_printed(node **root)
{
     if(*root==NULL) return;
     else
     {
         (*root)->printed=0;
         reinit_printed(&(*root)->left);
         reinit_printed(&(*root)->right);
     }
}          
if(root.value == requiredNode)
public void PrintNodes(Node Root, int requiredNode, int iDistance)

    {
        PrintNodesAtKDistance(Root, requiredNode, iDistance);
    }

    public int PrintNodesAtKDistance(Node root, int requiredNode, int iDistance)
    {
        if ((root == null) || (iDistance < 0))
            return -1;

        int lPath = -1, rPath = -1;

        if(root.value == requiredNode)
        {
            PrintChildNodes(root, iDistance);
            return iDistance - 1;
        }

        lPath = PrintNodesAtKDistance(root.left, requiredNode, iDistance);
        rPath = PrintNodesAtKDistance(root.right, requiredNode, iDistance);

        if (lPath > 0)
        {
            PrintChildNodes(root.right, lPath - 1);
            return lPath - 1;
        }
        else if(lPath == 0)
        {
            Debug.WriteLine(root.value);
        }

        if(rPath > 0)
        {
            PrintChildNodes(root.left, rPath - 1);
            return rPath - 1;
        }
        else if (rPath == 0)
        {
            Debug.WriteLine(root.value);
        }

        return -1;
    }

    public void PrintChildNodes(Node aNode, int iDistance)
    {
        if (aNode == null)
            return;

        if(iDistance == 0)
        {
            Debug.WriteLine(aNode.value);
        }

        PrintChildNodes(aNode.left, iDistance - 1);
        PrintChildNodes(aNode.right, iDistance - 1);
    }
// Java program to print all nodes at a distance k from given node

class BinaryTreePrintKDistance {
 Node root;

    /*
     * Recursive function to print all the nodes at distance k in tree (or
     * subtree) rooted with given root.
     */

    void printKDistanceForDescendant(Node targetNode, int currentDist,
            int inputDist) {
        // Base Case
        if (targetNode == null || currentDist > inputDist)
            return;

        // If we reach a k distant node, print it
        if (currentDist == inputDist) {
            System.out.print(targetNode.data);
            System.out.println("");
            return;
        }

        ++currentDist;
        // Recur for left and right subtrees
        printKDistanceForDescendant(targetNode.left, currentDist, inputDist);
        printKDistanceForDescendant(targetNode.right, currentDist, inputDist);
    }

    public int printkdistance(Node targetNode, Node currentNode,
            int inputDist) {

        if (currentNode == null) {
            return -1;
        }

        if (targetNode.data == currentNode.data) {
            printKDistanceForDescendant(currentNode, 0, inputDist);
            return 0;
        }

        int ld = printkdistance(targetNode, currentNode.left, inputDist);

        if (ld != -1) {

            if (ld + 1 == inputDist) {
                System.out.println(currentNode.data);

            } else {
                printKDistanceForDescendant(currentNode.right, 0, inputDist
                        - ld - 2);
            }

            return ld + 1;
        }

        int rd = printkdistance(targetNode, currentNode.right, inputDist);

        if (rd != -1) {

            if (rd + 1 == inputDist) {
                System.out.println(currentNode.data);

            } else {
                printKDistanceForDescendant(currentNode.left, 0, inputDist - rd
                        - 2);
            }

            return rd + 1;
        }

        return -1;

    }

    // Driver program to test the above functions
    @SuppressWarnings("unchecked")
    public static void main(String args[]) {
        BinaryTreePrintKDistance tree = new BinaryTreePrintKDistance();

        /* Let us construct the tree shown in above diagram */
        tree.root = new Node(20);
        tree.root.left = new Node(8);
        tree.root.right = new Node(22);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(12);
        tree.root.left.right.left = new Node(10);
        tree.root.left.right.right = new Node(14);
        Node target = tree.root.left;

        tree.printkdistance(target, tree.root, 2);
    }

    static class Node<T> {
        public Node left;
        public Node right;
        public T data;

        Node(T data) {
            this.data = data;
        }
    }

}