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