Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Also, we can use the same idea as preorder traversal: using a stack to simulate recursion. But for postorder, we need to insert a new value to the head of the list each time.
C++ Code:
/* * func: postorder_traversal * goal: postorder traverse the tree * @param root: root node of the tree * return: traversal list */ vector<int> postorder_traversal(TreeNode *root){ vector<int> result; if(root == nullptr){ return result; } stack<TreeNode *> postorder_helper; postorder_helper.emplace(root); while(!postorder_helper.empty()){ TreeNode *curr = postorder_helper.top(); result.emplace(result.begin(), curr->val); postorder_helper.pop(); if(curr->left){ postorder_helper.emplace(curr->left); } if(curr->right){ postorder_helper.emplace(curr->right); } } return result; }
Python Code:
# func: postorder traversal tree # @param root: root node of the tree # @return: traversal list def postorder_traversal(root): if not root: return [] result = [] stack = [root] while stack: curr = stack[-1] result.insert(0, curr.val) stack.pop(-1) if curr.left: stack.append(curr.left) if curr.right: stack.append(curr.right) return result
No comments:
Post a Comment