}voidhelp(vector<int> &vec, TreeNode*root){if(root == nullptr)return; help(vec, root->left); help(vec, root->right); vec.push_back(root->val); } }; //迭代classSolution {public: vector<int> postorderTraversal(TreeNode*root) {if(root == nullptr)return{}; vector<int>res; stack...
1、递归 1structTreeNode{2TreeNode *left;3TreeNode *right;4intval;5TreeNode(intx):val(x),left(NULL),right(NULL){}6}7vector<int> postorder(treeNode*root){8vector<int>res;9postordertraversal(root,res);10returnres;11}1213voidpostorderTraversal(TreeNode *root,vector<int> &res){14if(root...
*/voidtraversal(structTreeNode*root,int*countPointer,int*res){if(!root)return;traversal(root->left,countPointer,res);traversal(root->right,countPointer,res);res[(*countPointer)++]=root->val;}int*postorderTraversal(structTreeNode*root,int*returnSize){int*res=malloc(sizeof(int)*110);intcount=...
Given the root of a binary tree, return the postorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [3,2,1] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] Constraints: The number of the nodes in the tr...
Given a binary tree, return thepostordertraversal of its nodes' values. For example: Given binary tree{1,#,2,3}, 1 \ 2 / 3 1. 2. 3. 4. 5. return[3,2,1]. Note:Recursive solution is trivial, could you do it iteratively?
binary-tree-postorder-traversal public:vector<int>postorderTraversal(TreeNode*root){vector<int>result;stack<TreeNode*>st;TreeNode*p=root,*q=NULL;do{while(p)st.push(p),p=p->left;q=NULL;while(!st.empty()){p=st.top();st.pop();if(p->right==q)//右子树为空或者已经访问{result.push...
BinTree Left; /* 指向左子树*/ BinTree Right; /* 指向右子树 */ }TNode; 复制代码 三、如何创建一个二叉树? 先看代码再分析 void CreateBinaryTree ( BinTree *T ) { ElementType ch; scanf("%c",&ch); if (ch == '#') *T = NULL; ...
第二个元素再做交换。 定义两个指针p和q来指定需要交换的元素,指针pre记录当前结点的前驱结点,用来判断是否逆序。 voidrecoverTree(TreeNode *root) { pre= p = q =nullptr; dfs(root); swap(p->val, q->val); }voiddfs(TreeNode *root)
Postorder traversal Essentially, all three traversals work in roughly the same manner. They start at the root and visit that node and its children. The difference among these three traversal methods is the order with which they visit the node itself versus visiting its children. To help clarify...
Postorder traversal Essentially, all three traversals work in roughly the same manner. They start at the root and visit that node and its children. The difference among these three traversal methods is the order with which they visit the node itself versus visiting its children. To help clarify...