Sunday, November 2, 2014

Tree traverse methods conclusion

Binary Tree Inorder, Preorder and Postorder traverse. The recursive way is pretty straight forward, now we gonna discuss the iterative ways.

First of all, we should be very familiar with the recursive way to traverse trees. Then we can convert it to iterative ways. For example, inorder traverse.

inorderTraverse(root)
   if(root->left) inorderTraverse(root->left)
   visit root
   if(root->right)  inorderTraverse(root->right)


For iterative way, we need a stack and a pointer to keep track of the parents and the current node we are visiting. 

1)create an empty stack S.
2)initialize current node as root.
3)push current node to S and set cur = cur->left until cur == NULL
4) if current is NULL and stack is not empty then 
  a) visit the top item in S
  b) pop out the top item from S
  c) set cur as the right child of cur
  d) go to 3)
5) if cur and S be both NULL, then it's done.


The iterative way of pre order traverse has almost the same idea.

While the post order iterative traverse is a little bit harder.

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...