145. Binary Tree Postorder Traversal(js)

145. Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

题意:后序序遍历二叉树

代码如下:

var postorderTraversal = function(root) {
    if(!root) return [];
    let res=[],s=[];
    s.push(root);
    let head=root;
    while(s.length>0){
        let t=s[s.length-1];
        if((!t.left && !t.right)|| t.left===head || t.right===head){
            res.push(t.val);
            s.pop();
            head=t;
        }else{
            if(t.right) s.push(t.right);
            if(t.left) s.push(t.left);
        }
        
      
    }
    return res;
};

猜你喜欢

转载自www.cnblogs.com/xingguozhiming/p/11041993.html
今日推荐