translation
给定一个二叉树,返回其后续遍历的节点的值。例如:给定二叉树为 {1#, 2, 3} 1 2 / 3返回 [321]备注:用递归是微不足道的,你可以用迭代来完成它吗?
Original
returntheofits nodes‘ values.For example:Given binary tree {1,#,2,3}, 1 2 / 3return [3,2,1isit iteratively?
Analysis
Directly on the code ...
vector<int> postorderTraversal(TreeNode* root) { if (root != NULL) { postorderTraversal(root->left); postorderTraversal(root->right); v.push_back(root->val); } return v;}
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode (int x): Val (x), left (null), right (null) {}*};*/classSolution { Public: vector<int>VvoidPostordertraversaliter (TreeNode *root, Stack<TreeNode*>&STAC) {if(Root = NULL)return;BOOLHasleft = root->left! = NULL;BOOLHasright = root->right! = NULL; Stac.push (root);if(hasright) Stac.push (root->right);if(hasleft) Stac.push (root->left);if(!hasleft &&!hasright) v.push_back (root->val);if(Hasleft) {root = Stac.top (); Stac.pop (); Postordertraversaliter (Root, Stac); }if(Hasright) {root = Stac.top (); Stac.pop (); Postordertraversaliter (Root, Stac); }if(Hasleft | | hasright) v.push_back (Stac.top ()->val); Stac.pop (); } vector<int>Postordertraversal (treenode* root) { Stack<TreeNode*>Stac Postordertraversaliter (Root, Stac);returnV } };
There are two other similar topics:
Leetcode 94 binary Tree Inorder traversal (middle order traversal of binary trees) + (binary tree, iteration)
Leetcode 144 binary Tree preorder traversal (binary trees pre-sequence traversal) + (binary tree, iteration)
Leetcode 145 binary Tree Postorder Traversal (subsequent traversal of binary trees) + (binary tree, iteration)