返回介绍

lcof2 / 剑指 Offer II 052. 展平二叉搜索树 / README

发布于 2024-06-17 01:04:41 字数 10136 浏览 0 评论 0 收藏 0

剑指 Offer II 052. 展平二叉搜索树

题目描述

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

 

示例 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:

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

 

提示:

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

 

注意:本题与主站 897 题相同: https://leetcode.cn/problems/increasing-order-search-tree/

解法

方法一

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def increasingBST(self, root: TreeNode) -> TreeNode:
    head, tail = None, None
    stack = []
    cur = root
    while stack or cur:
      while cur:
        stack.append(cur)
        cur = cur.left
      cur = stack.pop()
      if not head:
        head = cur
      else:
        tail.right = cur
      tail = cur
      cur.left = None
      cur = cur.right
    return head
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode() {}
 *   TreeNode(int val) { this.val = val; }
 *   TreeNode(int val, TreeNode left, TreeNode right) {
 *     this.val = val;
 *     this.left = left;
 *     this.right = right;
 *   }
 * }
 */
class Solution {
  public TreeNode increasingBST(TreeNode root) {
    TreeNode head = null, tail = null;
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode cur = root;
    while (!stack.isEmpty() || cur != null) {
      while (cur != null) {
        stack.push(cur);
        cur = cur.left;
      }
      cur = stack.pop();
      if (head == null) {
        head = cur;
      } else {
        tail.right = cur;
      }
      tail = cur;
      cur.left = null;
      cur = cur.right;
    }
    return head;
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  TreeNode* increasingBST(TreeNode* root) {
    TreeNode *head = nullptr, *tail = nullptr;
    stack<TreeNode*> stk;
    TreeNode* cur = root;
    while (!stk.empty() || cur != nullptr) {
      while (cur != nullptr) {
        stk.push(cur);
        cur = cur->left;
      }
      cur = stk.top();
      stk.pop();
      if (head == nullptr) {
        head = cur;
      } else {
        tail->right = cur;
      }
      tail = cur;
      cur->left = nullptr;
      cur = cur->right;
    }
    return head;
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func increasingBST(root *TreeNode) *TreeNode {
  var head, tail *TreeNode
  stack := make([]*TreeNode, 0)
  cur := root
  for len(stack) > 0 || cur != nil {
    for cur != nil {
      stack = append(stack, cur)
      cur = cur.Left
    }
    cur = stack[len(stack)-1]
    stack = stack[:len(stack)-1]
    if head == nil {
      head = cur
    } else {
      tail.Right = cur
    }
    tail = cur
    cur.Left = nil
    cur = cur.Right
  }
  return head
}
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 *   }
 * }
 */

function increasingBST(root: TreeNode | null): TreeNode | null {
  const dummy = new TreeNode();
  let cur = dummy;
  const dfs = (root: TreeNode | null) => {
    if (root == null) {
      return;
    }
    dfs(root.left);
    cur.right = new TreeNode(root.val);
    cur = cur.right;
    dfs(root.right);
  };
  dfs(root);
  return dummy.right;
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//   TreeNode {
//     val,
//     left: None,
//     right: None
//   }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, vals: &mut Vec<i32>) {
    if root.is_none() {
      return;
    }
    let node = root.as_ref().unwrap().borrow();
    Self::dfs(&node.left, vals);
    vals.push(node.val);
    Self::dfs(&node.right, vals);
  }

  pub fn increasing_bst(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
    let mut vals = Vec::new();
    Self::dfs(&root, &mut vals);
    let mut dummy = Rc::new(RefCell::new(TreeNode::new(0)));
    for &val in vals.iter().rev() {
      let mut dummy = dummy.as_ref().borrow_mut();
      dummy.right = Some(
        Rc::new(
          RefCell::new(TreeNode {
            val,
            left: None,
            right: dummy.right.take(),
          })
        )
      );
    }
    let ans = dummy.as_ref().borrow_mut().right.take();
    ans
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   struct TreeNode *left;
 *   struct TreeNode *right;
 * };
 */

struct TreeNode* dfs(struct TreeNode* root, struct TreeNode* cur) {
  if (!root) {
    return cur;
  }
  cur = dfs(root->left, cur);
  cur->right = malloc(sizeof(struct TreeNode));
  cur->right->val = root->val;
  cur->right->left = NULL;
  cur->right->right = NULL;
  cur = cur->right;
  return dfs(root->right, cur);
}

struct TreeNode* increasingBST(struct TreeNode* root) {
  struct TreeNode* dummy = malloc(sizeof(struct TreeNode));
  dfs(root, dummy);
  return dummy->right;
}

方法二

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def increasingBST(self, root: TreeNode) -> TreeNode:
    def dfs(root: TreeNode):
      if root is None:
        return

      dfs(root.left)

      nonlocal cur
      cur.right = root
      root.left = None
      cur = cur.right

      dfs(root.right)

    cur = dummy = TreeNode()
    dfs(root)
    return dummy.right
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode() {}
 *   TreeNode(int val) { this.val = val; }
 *   TreeNode(int val, TreeNode left, TreeNode right) {
 *     this.val = val;
 *     this.left = left;
 *     this.right = right;
 *   }
 * }
 */
class Solution {
  private TreeNode cur;

  public TreeNode increasingBST(TreeNode root) {
    TreeNode dummy = new TreeNode();
    cur = dummy;
    dfs(root);
    return dummy.right;
  }

  private void dfs(TreeNode root) {
    if (root == null) {
      return;
    }
    dfs(root.left);
    cur.right = root;
    root.left = null;
    cur = cur.right;
    dfs(root.right);
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  TreeNode* increasingBST(TreeNode* root) {
    TreeNode* dummy = new TreeNode();
    TreeNode* cur = dummy;
    function<void(TreeNode*)> dfs = [&](TreeNode* root) {
      if (!root) {
        return;
      }
      dfs(root->left);
      cur->right = root;
      root->left = nullptr;
      cur = cur->right;
      dfs(root->right);
    };
    dfs(root);
    return dummy->right;
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func increasingBST(root *TreeNode) *TreeNode {
  dummy := &TreeNode{}
  cur := dummy
  var dfs func(*TreeNode)
  dfs = func(root *TreeNode) {
    if root == nil {
      return
    }
    dfs(root.Left)
    root.Left = nil
    cur.Right = root
    cur = root
    dfs(root.Right)
  }
  dfs(root)
  return dummy.Right
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文