【问题标题】:Finding nth inorder node of a binary tree where each node contains number of left nodes in its subtree查找二叉树的第 n 个中序节点,其中每个节点包含其子树中的左节点数
【发布时间】:2018-08-20 14:07:50
【问题描述】:

我遇到了这个问题,但似乎无法在任何地方找到解决方案。

给定一棵二叉树,其中每个节点都包含一个数字,表示左节点的数量 在其子树中,编写一个返回第 n 个中序的函数 遍历节点。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
        self.leftNodes = 0

查找nth node of inorder traversal 相当简单,但我如何使用有关左节点数的信息来改进流程?

【问题讨论】:

标签: algorithm binary-tree


【解决方案1】:

正如@m69 给出的提示 - 您可以使用左节点计数来避免一些不必要的步骤。

假设有一棵树,其中根在他的左子树中有 10 个节点:那么当询问第 n 个节点时(按顺序),如果 n= 1-10 则答案将在左子树中。但是,如果n= 11 那么答案将是根,否则答案将在正确的子树中。

考虑以下伪代码:

findNnode(TreeNode root, int n) {
    if (root.leftNodes + 1 == n )
        return root; 
    if (root.leftNodes <= n)
        return findNnode(root.left, n)
    newN = n - root.leftNodes - 1; // after substract all node who came before in in-order
    return findNnode(root.right, newN)
}  

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多