二叉树遍历,交换节点

public class TreeTest {

    public static void main(String[] args){

        TreeTest test = new TreeTest();

        TreeNode root = test.createTree();

        test.outputTreeValue(root);

        System.out.println();

        test.swapLeftRightNode(root);

        test.outputTreeValue(root);

    }

    public void outputTreeValue(TreeNode root){

        if(root != null){
            System.out.print(root.getValue() + " ");
            if(root.getLeftNode() != null){
                outputTreeValue(root.getLeftNode());
            }
            if(root.getRightNode() != null){
                outputTreeValue(root.getRightNode());
            }
        }

    }

    public void swapLeftRightNode(TreeNode root){
        if(root != null){
            //交换左右节点
            TreeNode temp = root.getLeftNode();
            root.setLeftNode(root.getRightNode());
            root.setRightNode(temp);
            if(root.getLeftNode() != null){
                swapLeftRightNode(root.getLeftNode());
            }
            if(root.getRightNode() != null){
                swapLeftRightNode(root.getRightNode());
            }
        }

    }


    public TreeNode createTree(){
        TreeNode root = new TreeNode();

        root.setValue(0);

        TreeNode temp1 = new TreeNode();

        temp1.setValue(1);

        TreeNode temp2 = new TreeNode();

        temp2.setValue(2);
        //根节点挂载两个子节点
        root.setLeftNode(temp1);
        root.setRightNode(temp2);


        TreeNode temp3 = new TreeNode();

        temp3.setValue(3);

        TreeNode temp4 = new TreeNode();

        temp4.setValue(4);

        temp1.setLeftNode(temp3);
        temp1.setRightNode(temp4);

        TreeNode temp5 = new TreeNode();

        temp5.setValue(5);

        TreeNode temp6 = new TreeNode();

        temp6.setValue(6);
        temp2.setLeftNode(temp5);
        temp2.setRightNode(temp6);
        TreeNode temp7 = new TreeNode();

        temp7.setValue(7);

        temp3.setLeftNode(temp7);

        return root;

    }




    /**
     * 树的节点
     */
    class TreeNode{
        private Integer value;

        private TreeNode leftNode;

        private TreeNode rightNode;

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public TreeNode getLeftNode() {
            return leftNode;
        }

        public void setLeftNode(TreeNode leftNode) {
            this.leftNode = leftNode;
        }

        public TreeNode getRightNode() {
            return rightNode;
        }

        public void setRightNode(TreeNode rightNode) {
            this.rightNode = rightNode;
        }
    }
}

你可能感兴趣的:(二叉树遍历,交换节点)