LeetCode:Binary Tree Postorder Traversal

题目:Binary Tree Postorder Traversal

二叉树的后序遍历,题目要求是采用非递归的方式,这个在上数据结构的课时已经很清楚了,二叉树的非递归遍历不管采用何种方式,都需要用到栈结构作为中转,代码很简单,见下:

 1 struct TreeNode {

 2     int            val;

 3     TreeNode*    left;

 4     TreeNode*    right;

 5     TreeNode(int x): val(x), left(NULL),right(NULL) {}

 6 };

 7 

 8 vector<int> preorderTraversal(TreeNode *root) //非递归的后序遍历(用栈实现)

 9 {

10     if (NULL == root) {

11         return vector<int>();

12     }

13     

14     stack<TreeNode *> tree_stack;

15     vector<int> tree_vector;

16 

17     tree_stack.push(root);

18     TreeNode *p = NULL;

19     while (!tree_stack.empty()) {

20         TreeNode *pTemp = tree_stack.top();

21         if ((pTemp->left == NULL && pTemp->right == NULL) || ((p != NULL) && (pTemp->left == p || pTemp->right == p))) {

22             tree_vector.push_back(pTemp->val);

23             tree_stack.pop();

24             

25             p = pTemp;

26         }

27         else {

28             while(pTemp) {

29                 if (pTemp->right != NULL) 

30                     tree_stack.push(pTemp->right);

31 

32                 if (pTemp->left != NULL)

33                     tree_stack.push(pTemp->left);

34                 pTemp = pTemp->left;

35             }

36         }

37     }

38     return tree_vector;

39 }

 

你可能感兴趣的:(LeetCode)