数据结构——距离根节点为k的节点

    xiaoxiao2021-12-14  19

    原文地址:Print nodes at k distance from root

    已知一个树的根节点,一个整数k。打印出所有距离根节点为k的节点。

    例如,在下面的树中, 4, 5 & 8距离根节点的距离是2。

    这个问题可以用递归来解决。

    // Java program to print nodes at k distance from root /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } class BinaryTree { Node root; void printKDistant(Node node, int k) { if (node == null) return; if (k == 0) { System.out.print(node.data + " "); return; } else { printKDistant(node.left, k - 1); printKDistant(node.right, k - 1); } } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(8); tree.printKDistant(tree.root, 2); } } // This code has been contributed by Mayank Jaiswal

    上面的代码输出4,5和8。

    时间复杂度是:O(n),在这里n是已知二叉树中节点的数目。

    转载请注明原文地址: https://ju.6miu.com/read-970052.html

    最新回复(0)