码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-10-22 14:38:08      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:python   tree   algorithm   

参考: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


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

标签:python   tree   algorithm   

原文地址:http://blog.csdn.net/tanzhangwen/article/details/40375029

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!