leetcode[145]:Binary Tree Postorder Traversal
来源:互联网 发布:php 订单号生成算法 编辑:程序博客网 时间:2024/05/16 02:03
Binary Tree Postorder Traversal
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].
Note: Recursive solution is trivial, could you do it iteratively?
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; *//** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* postorderTraversal(struct TreeNode* root, int* returnSize) { struct TreeNode stack[1000]; struct TreeNode *tmp; int i=0; int res[100000]={0},*result; int k=0; if(!root) {*returnSize=k;return NULL;} tmp=root; while(1) { if(!tmp->left && !tmp->right) { res[k++] = tmp->val; if(i==0) break; tmp=&stack[--i]; continue; } stack[i++] = *tmp; if( tmp->left ) { tmp=stack[i-1].left; stack[i-1].left=NULL; continue; } if( tmp->right) { tmp=stack[i-1].right; stack[i-1].right=NULL; } } * returnSize =k; result= (int*)malloc(sizeof(int*)*k); for(i=0;i<k;i++) { result[i]=res[i]; } return result;}
寻找叶子,先左后右,压栈时将左子树赋空,左子树为空时,将右子树赋空,叶子可以输出了。
0 0
- LeetCode(145)Binary Tree Postorder Traversal
- LeetCode: Binary Tree Postorder Traversal [145]
- LeetCode 145 Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode || 145、Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode 145
- Leetcode[145]-Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- leetcode(145):Binary Tree Postorder Traversal
- leetcode-145-Binary Tree Postorder Traversal
- [Leetcode 145, Hard] Binary Tree Postorder Traversal
- leetcode[145]:Binary Tree Postorder Traversal
- [leetcode-145]Binary Tree Postorder Traversal(c++)
- Leetcode #145 Binary Tree Postorder Traversal
- LeetCode 145 : Binary Tree Postorder Traversal
- LeetCode 145: Binary Tree Postorder Traversal
- 【LEETCODE】145-Binary Tree Postorder Traversal
- LeetCode 145 Binary Tree Postorder Traversal
- 高质量C++/C编程指南
- [Spring MVC] - Annotation验证
- jar包命令行、eclipse下能运行但是双击不能运行,提示找不到main class
- Linux线程
- hd-1092:A+B for Input-Output Practice (IV)
- leetcode[145]:Binary Tree Postorder Traversal
- HDOJ 2035 人见人爱A^B-----二分快速求幂
- 【idea】关于书,我的考虑
- MFC使用PreTranslateMessage实现键盘监听
- 调用GP服务
- 防止NSTimer和调用对象之间的循环引用
- 3D数学 矩阵和线性变换之镜像
- 开始刷刷Leetcode—leetcode第二题
- arcgis JavaScript调用GP服务自动生成等值面