File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode.cn id=145 lang=javascript
3+ *
4+ * [145] 二叉树的后序遍历
5+ */
6+
7+ import { node } from "webpack" ;
8+
9+ // @lc code=start
10+ /**
11+ * Definition for a binary tree node.
12+ * function TreeNode(val, left, right) {
13+ * this.val = (val===undefined ? 0 : val)
14+ * this.left = (left===undefined ? null : left)
15+ * this.right = (right===undefined ? null : right)
16+ * }
17+ */
18+ /**
19+ * @param {TreeNode } root
20+ * @return {number[] }
21+ */
22+ var postorderTraversal = function ( root ) {
23+ // 递归
24+ const result = [ ] ;
25+ const postOrder = ( node ) => {
26+ if ( node ) {
27+ postOrder ( node . left ) ;
28+ postOrder ( node . right ) ;
29+ result . push ( node . val ) ;
30+ }
31+ }
32+ postOrder ( root ) ;
33+
34+ return result ;
35+
36+ // return postOrderIterate(root);
37+ } ;
38+
39+ // 迭代
40+ // 中右左
41+ // => reverse
42+ // 左右中
43+
44+ function postOrderIterate ( root ) {
45+ if ( ! root ) return [ ] ;
46+ const result = [ ] ;
47+ const stack = [ root ] ;
48+
49+ while ( stack . length ) {
50+ node = stack . pop ( ) ;
51+ result . push ( node . val ) ;
52+
53+ node . left && stack . push ( node . left ) ;
54+ node . right && stack . push ( node . right ) ;
55+ }
56+
57+ return result . reverse ( ) ;
58+ }
59+ // @lc code=end
60+
You can’t perform that action at this time.
0 commit comments