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

二叉树的后序遍历

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

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @return int整型一维数组
     */
    public int[] postorderTraversal (TreeNode root) {
        // write code here
        List<Integer> list = new ArrayList<>();
        postOrder3(root, list);
        int[] array = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        return array;
    }
    public void postOrder3(TreeNode root, List<Integer> list){
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;

        while(true){
            while(root != null && root != pre){
                stack.push(root);
                root = root.left;
            }
            if(!stack.empty())
                root = stack.pop();
            else{
                break;
            }
            if(root.right != null && pre != root.right){
                stack.push(root);
                root = root.right;
            }else {
                list.add(root.val);
                pre = root;
            }
        }
    }
    public void postOrder2(TreeNode root, List<Integer> list) {
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        TreeNode pre = null;
        if (root == null)
            return;
        stack1.push(root);

        while (!stack1.empty()) {
            root = stack1.pop();
            stack2.push(root);
            if(root.left != null){
                stack1.push(root.left);
            }
            if(root.right != null){
                stack1.push(root.right);
            }
        }
        while(!stack2.empty()){
            list.add(stack2.pop().val);
        }
    }
    public void postOrder(TreeNode root, List<Integer> list) {
        if (root == null)
            return;
        postOrder(root.left, list);
        postOrder(root.right, list);
        list.add(root.val);
    }
}

全部评论
这说明二叉树的实现有很多种,但是据我所知思路只有两种,多写就能理解了
点赞 回复 分享
发布于 2024-06-16 11:23 上海

相关推荐

点赞 评论 收藏
分享
03-13 16:51
已编辑
门头沟学院 硬件开发
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务