zoukankan      html  css  js  c++  java
  • [GeeksForGeeks] Populate inorder successor for all nodes in a binary search tree

    Given a binary search tree with the following tree node definition.

    next points to a node's inorder successor.

    Populate inorder successor for all nodes in this bst.

     1 class TreeNodeWithNext {
     2     int val;
     3     TreeNodeWithNext left, right, next;
     4     public TreeNodeWithNext(int v) {
     5         this.val = v;
     6         this.left = null;
     7         this.right = null;
     8         this.next = null;
     9     }
    10 }

    Recursive solution using reverse in order traversal.

    Since we need to set each node's next to its inorder successor, in order traversal is the natural way to acheive this.

    We can either traverse in order from smaller value nodes to bigger value nodes or vice versa.

     1 private TreeNodeWithNext prev = null;
     2 public void populateInorderSuccessorRecursion(TreeNodeWithNext root) {
     3     if(root == null) {
     4         return;
     5     }
     6     populateInorderSuccessorRecursion(root.left);
     7     if(prev != null) {
     8         prev.next = root;
     9     }
    10     prev = root;
    11     populateInorderSuccessorRecursion(root.right);
    12 }
     1 public class PopulateInorderSuccessor {
     2     private TreeNodeWithNext next = null;
     3     public void populateInorderSuccessorRecursion(TreeNodeWithNext root) {
     4         if(root == null) {
     5             return;
     6         }
     7         populateInorderSuccessorRecursion(root.right);
     8         root.next = next;
     9         next = root;
    10         populateInorderSuccessorRecursion(root.left);
    11     }
    12 }

    Iterative solution.

    Instead of using recursion, we can use a stack to simulate the recursive process and get the following iterative solution.

     1 public void populateInorderSuccessorIterative(TreeNodeWithNext root) {
     2     if(root == null) {
     3         return;
     4     }
     5     TreeNodeWithNext prev = null, curr = root;
     6     Stack<TreeNodeWithNext> stack = new Stack<TreeNodeWithNext>();
     7     while(curr != null || !stack.isEmpty()) {
     8         while(curr != null) {
     9             stack.push(curr);
    10             curr = curr.left;
    11         }
    12         curr = stack.pop();
    13         if(prev != null) {
    14             prev.next = curr;
    15         }
    16         prev = curr;
    17         curr = curr.right;
    18     }
    19 }
  • 相关阅读:
    编译Openmv固件&增加串口
    边缘 AI 平台的比较
    CVPR2021 | 重新思考BatchNorm中的Batch
    ICCV2021 |重新思考人群中的计数和定位:一个纯粹基于点的框架
    ICCV2021 | 重新思考视觉transformers的空间维度
    CVPR2021 | Transformer用于End-to-End视频实例分割
    漫谈CUDA优化
    AAAI 2021 最佳论文公布
    综述专栏 | 姿态估计综述
    为什么GEMM是深度学习的核心
  • 原文地址:https://www.cnblogs.com/lz87/p/7416246.html
Copyright © 2011-2022 走看看