题解 | #二叉树的后序遍历#

二叉树的后序遍历

https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541

import java.util.*;
public class Solution {
    public int[] postorderTraversal (TreeNode root) {
        // write code here
        if(root==null)return new int[0];
        List<Integer> list = new ArrayList<>();
        postOr(list,root);
        int[] res=new int[list.size()];
        for(int i=0;i<res.length;i++){
            res[i]=list.get(i);
        }
        return res;
    }
    
  //递归方法
    public void postOr(List<Integer> list,TreeNode t){
        if(t.left!=null) postOr(list,t.left);
        if(t.right!=null) postOr(list,t.right);
        list.add(t.val);
    }
}

递归遍历树

按题意所说,通过递归遍历树来获得其后续遍历

每次先遍历左子树,再右子树,最后根

全部评论

相关推荐

评论
3
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务