二叉树中的后序遍历面临死代码

问题描述 投票:0回答:0

在这里,我试图按后序遍历我的二叉树(硬编码)。但是在第一个 esle 之后(我用 ***** 标记它是死代码。你能帮忙吗?这是我的代码。 `包 BnaryTree;

import java.util.Stack;

public class PostOrder {
private TreeNode root;

private class TreeNode {
    private TreeNode left;
    private TreeNode rigth;
    private int data;

    public TreeNode(int data) {
        this.data = data;
    }

}
public void createBinaryTree() {
    TreeNode first = new TreeNode(1);
    TreeNode second = new TreeNode(2);
    TreeNode three = new TreeNode(3);
    TreeNode four = new TreeNode(4);
    TreeNode five = new TreeNode(5);


    root = first;
    first.left = second;
    first.rigth= three;
    second.left=four; 
    second.rigth= five;
    
    
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    PostOrder post= new PostOrder();
    post.createBinaryTree();
    post.postOrder();
}

public void postOrder() {
    TreeNode current = root;
    Stack<TreeNode> stack = new Stack<>();
    while (!stack.isEmpty() && current != null) {
        if (current != null) {
            stack.push(current);
            current = current.left;
                    //*****
        } else {
            TreeNode temp = stack.pop().rigth;
            if (temp == null) {
                temp = stack.pop();
                System.out.println(temp.data + " ");
                while (!stack.isEmpty() & temp == stack.pop().rigth) {
                    temp = stack.pop();
                    System.out.println(temp.data + " ");
                }
            } else {
                current = temp;
            }
        }
    }
}
}`

Eclipse 正在发送消息(死代码),但我不确定为什么。谢谢。

java binary-tree postorder
© www.soinside.com 2019 - 2024. All rights reserved.