998. Maximum Binary Tree II

We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.

Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine:

  • If A is empty, return null.
  • Otherwise, let A[i] be the largest element of A.  Create a root node with valueA[i].
  • The left child of root will be Construct([A[0], A[1], ..., A[i-1]])
  • The right child of root will be Construct([A[i+1], A[i+2], ..., A[A.length - 1]])
  • Return root.

Note that we were not given A directly, only a root node root = Construct(A).

Suppose B is a copy of A with the value val appended to it.  It is guaranteed that Bhas unique values.

Return Construct(B).

 

Example 1:

Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: A = [1,4,2,3], B = [1,4,2,3,5]

Example 2:

Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: A = [2,1,5,4], B = [2,1,5,4,3]

Example 3:

Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: A = [2,1,5,3], B = [2,1,5,3,4]

题解:

在上一篇博客的基础上解的题

戳这里QAQ~~查看具体思路

大概就是在给定的一颗二叉树上,额外附加一个值val,建立另一颗二叉树,这个二叉树的建立规则请查看上一篇博客。

思路:

(一)、初始化一个vector用来存放给定的二叉树中序遍历出来的数值,然后在vector尾端加上val。然后再开始建立一颗新的二叉树。

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
        if(!root)
            return NULL;
        vector<int>res;
        Inorder(root,res);
        res.push_back(val);
        vector<TreeNode*>Root;
        for(int i=0;i<res.size();i++)
        {
            TreeNode* add=new TreeNode(res[i]);
            if(Root.empty())
                Root.push_back(add);
            else
            {
                while(!Root.empty()&&Root.back()->val<res[i])
                {
                    add->left=Root.back();
                    Root.pop_back();
                }
                if(!Root.empty())
                    Root.back()->right=add;
                Root.push_back(add);
            }
        }
        return Root.front();
    }
     void Inorder(TreeNode* root,vector<int>& res)
    {
        if(!root)
            return ;
        Inorder(root->left,res);
        res.push_back(root->val);
        Inorder(root->right,res);
    }
};

运行结果:

 

(二)、直接在原始的二叉树上寻找到val的插入点。

根据例子所示:附加值val是直接放在二叉树中序序列的最后的。所以:

假设:node代表当前节点,prev代表node的父节点

1.重复以下代码:

     if(!node&&val<node->val) 继续,else 结束。

2.,则val应该是prev的右孩子,node应该是val的左孩子。

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
       TreeNode *node=root,*prev=NULL;
        while(node&&val<node->val)
        {
            prev=node;
            node=node->right;
        }
        auto n=new TreeNode(val);
        if(prev)
          prev->right=n;
        else
            root=n;
        n->left=node;
    return root;
    }
};

 

As an AI language model, I cannot provide you with the exact solution you need without further details. However, here is a general approach to find the longest distance in a binary tree using Python: 1. Define a class for a binary tree node with attributes for the node value, left child, and right child. 2. Define a function that recursively traverses the binary tree and returns the height of the tree starting from a given node. 3. Define a function that recursively traverses the binary tree and returns the longest distance between two nodes in the tree. 4. In the function defined in step 3, for each node, calculate the longest distance that passes through that node and update the maximum distance seen so far. 5. Call the function defined in step 3 starting from the root node of the binary tree. Here is a sample implementation of the above approach: ``` class Node: def __init__(self, value): self.value = value self.left = None self.right = None def height(root): if root is None: return 0 return 1 + max(height(root.left), height(root.right)) def longest_distance(root): if root is None: return 0 left_height = height(root.left) right_height = height(root.right) left_distance = longest_distance(root.left) right_distance = longest_distance(root.right) return max(left_height + right_height, max(left_distance, right_distance)) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) print(longest_distance(root)) ``` This code will output the longest distance between any two nodes in the binary tree.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值