(刷题笔记) Leetcode 897. 递增顺序查找树

    技术2024-07-30  83

    目录

    题目解题思路代码(C++)

    题目

    给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。

    示例 :

    输入:[5,3,6,2,4,null,8,1,null,null,null,7,9] 5 / \ 3 6 / \ \ 2 4 8 / / \ 1 7 9 输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] 1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9

    提示:

    给定树中的结点数介于 1 和 100 之间。 每个结点都有一个从 0 到 1000 范围内的唯一整数值。

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/increasing-order-search-tree

    解题思路

    这道题与面试题 17.12. BiNode是一模一样的。 不过隔了一段时间又换了一种说法之后,我就只记得我写过,但是不记得怎么写的,然后就顺着写了一个中序遍历,但是没办法返回到头结点,然后就回来看了一下这个答案。

    代码(C++)

    /** * 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* increasingBST(TreeNode* root) { stack<TreeNode*> st; TreeNode* temp=root; TreeNode* now=NULL; while(!st.empty()||temp!=NULL){ while(temp){ st.push(temp); temp=temp->right; } temp=st.top(); st.pop(); temp->right=now; now=temp; temp=temp->left; now->left=NULL; } return now; } };

    递归

    /** * 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* now=NULL; void dfs(TreeNode* root){ if(root==NULL) return; dfs(root->right); root->right=now; now=root; dfs(root->left); root->left=NULL; } TreeNode* increasingBST(TreeNode* root) { dfs(root); return now; } };
    Processed: 0.023, SQL: 9