Morris Traversal: 非递归不用栈实现对树的中序遍历

参考:http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/

<pre name="code" class="plain">1. Initialize current as root
2. While current is not NULL
   If current does not have left child
      a) Print current’s data
      b) Go to the right child, i.e., current = current->right
   Else
      a) Make current as right child of the rightmost node in current's left subtree
      b) Go to this left child, i.e., current = current->left
When we do 2.Else, for the first round it will execute 2.Else.a/b. When finish the steps and return back,we check again and reset the rightmost node in current's left subtree as null. That is the following statement:
      a') Find the rightmost node in current's left subtree (its right child is current) and set its right child as null
      b') Go to the right child

        cur = root
        while cur is not None:
            if cur.left is None:
                cur = cur.right
            else:
                ptr = cur.left
                while ptr.right != None and ptr.right != cur:
                    ptr = ptr.right
                if ptr.right == None:    //Else a/b, the rightmost node in current's left subtree
                    ptr.right = cur
                    cur = cur.left
                else:                    //Else a'/b', restore the right child of the right most node in current's left subtree
                    ptr.right = None
                    cur = cur.right

题目举例:

https://oj.leetcode.com/problems/recover-binary-search-tree/

https://oj.leetcode.com/problems/validate-binary-search-tree/

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a boolean
    def isValidBST(self, root):
        ans = True
        pre,cur = None,root
        while cur is not None:
            if cur.left is None:
                pre = cur
                cur = cur.right
            else:
                ptr = cur.left
                while ptr.right != None and ptr.right != cur:
                    ptr = ptr.right
                if ptr.right == None:
                    ptr.right = cur
                    cur = cur.left
                else:
                    ptr.right = None
                    pre = cur
                    cur = cur.right
            if pre != None and cur != None:
                if pre.val >= cur.val:
                    ans = False
        return ans
时间: 2024-10-04 23:12:50

Morris Traversal: 非递归不用栈实现对树的中序遍历的相关文章

C++用非递归实现二叉树的前序排列,中序排列,后续排列

前序排列的非递归实现: Template<class T> Void PreOrder(BinaryTreeNode<T> *t) { stack <BinaryTreeNode<T> *> S(Maxlength); BinaryTreeNode<T> *p=t; do{ while(p){ visit(p);//访问P S.Add(p); p=p->LeftChild; } If(!S.IsEmpty()){ S.Delete(p);

145. Binary Tree Postorder Traversal非递归,栈实现

Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 2 / 3 return [3,2,1]. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; *

Java数据结构系列之——树(4):二叉树的中序遍历的递归与非递归实现

package tree.binarytree; import java.util.Stack; /** * 二叉树的中序遍历:递归与非递归实现 * * @author wl * */ public class BiTreeInOrder { // 中序遍历的递归实现 public static void biTreeInOrderByRecursion(BiTreeNode root) { if (root == null) { return; } biTreeInOrderByRecursi

94. Binary Tree Inorder Traversal(非递归实现二叉树的中序遍历)

Given a binary tree, return the inorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively? 方法一:递归 /** * Definition for a binary tree node. * publ

leetcode | 二叉树的前序遍历、中序遍历、后续遍历的非递归实现

Binary Tree Preorder Traversal:https://leetcode.com/problems/binary-tree-preorder-traversal/ Binary Tree Inorder Traversal :https://leetcode.com/problems/binary-tree-inorder-traversal/ Binary Tree Postorder Traversal:https://leetcode.com/problems/bin

二叉树(2)----中序遍历,递归和非递归实现

1.二叉树定义: typedef struct BTreeNodeElement_t_ { void *data; } BTreeNodeElement_t; typedef struct BTreeNode_t_ { BTreeNodeElement_t *m_pElemt; struct BTreeNode_t_ *m_pLeft; struct BTreeNode_t_ *m_pRight; } BTreeNode_t; 2.中序遍历 定义:首先访问左子树,然后访问根节点,最后访问右子树

树的非递归遍历(中序遍历)

中序 遍历的几种情况 分析1:什么时候访问根.什么时候访问左子树.什么访问右子树 当左子树为空或者左子树已经访问完毕以后,再访问根 访问完毕根以后,再访问右子树. 分析2:非递归遍历树,访问结点时,为什么是栈,而不是其他模型(比如说是队列). 先走到的后访问.后走到的先访问,显然是栈结构 分析3:结点所有路径情况 步骤1: 如果结点有左子树,该结点入栈: 如果结点没有左子树,访问该结点: 步骤2: 如果结点有右子树,重复步骤1: 如果结点没有右子树(结点访问完毕),根据栈顶指示回退,访问栈顶元素

完全二叉树的链式存储结构的转化 &amp; 非递归中序遍历二叉树

1 /* 2 * 二叉树 3 * 4 * (将完全二叉树的数组形式改为链表形式) 5 * 6 * 1 7 * 2 3 8 * 4 5 6 7 9 * 8 10 * 11 */ 12 #include <iostream> 13 #define MAX 10 14 using namespace std; 15 16 typedef struct btnode{ 17 int data; 18 struct btnode * lchild; 19 struct btnode * rchild;

[C++]LeetCode: 93 Binary Search Tree Iterator (经典题,非递归的中序遍历)

题目: Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and u