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

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

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值