Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

递增顺序搜索树 #135

Open
yankewei opened this issue Apr 25, 2021 · 1 comment
Open

递增顺序搜索树 #135

yankewei opened this issue Apr 25, 2021 · 1 comment
Labels
题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单 递归 题目包含递归解法

Comments

@yankewei
Copy link
Owner

给你一棵二叉搜索树,请你 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。

示例 1:

示例1

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

示例 2:

示例2

输入:root = [5,1,7]
输出:[1,null,5,null,7]

提示:

  • 树中节点数的取值范围是 [1, 100]
  • 0 <= Node.val <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-order-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单 递归 题目包含递归解法 labels Apr 25, 2021
@yankewei yankewei changed the title 897. 递增顺序搜索树 递增顺序搜索树 Apr 25, 2021
@yankewei
Copy link
Owner Author

深度优先搜索

很明显就是DFS的题目,中序遍历就是,先左,再中间,然后右边。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func increasingBST(root *TreeNode) *TreeNode {
    ret := &TreeNode{}
    dummy := ret
    var dfs func(r *TreeNode)
    dfs = func (r *TreeNode) {
        if r == nil {
            return
        }
        
        dfs(r.Left)
        ret.Right = r
        r.Left = nil
        ret = ret.Right

        dfs(r.Right)
    }
    dfs(root)
    return dummy.Right
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单 递归 题目包含递归解法
Projects
None yet
Development

No branches or pull requests

1 participant