Data structure and algorithm exchange left and right subtrees of binary tree

Swap the left and right subtrees of a binary tree

Data structure and algorithm exchange left and right subtrees of binary tree

topic

Thought

Recursive exchange is enough, and the front/middle/post order are all available

Code

short version

public TreeNode swapLeftAndRightNode(TreeNode root) {
    
    
    if(root!=null){
    
    
        swapLeftAndRightNode(root.left);
        swapLeftAndRightNode(root.right);
        TreeNode temp=root.left;
        root.left=root.right;
        root.right=temp;
    }
   
}

refactored version

/**
 * 交换左右子树
 *
 * @param root 根节点
 * @return 交换后的新树
 */
public TreeNode swapLeftAndRightNode(TreeNode root) {
    if (root != null) {
        swapLeftAndRightNode(root.left);
        swapLeftAndRightNode(root.right);
	swap(root);
    }
    return root;
}

private void swap(TreeNode root) {
    if (root != null) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
}

Guess you like

Origin blog.csdn.net/qq_45074341/article/details/126902416
Recommended