1. 程式人生 > >leetcode Invert Binary Tree

leetcode Invert Binary Tree

Invert Binary Tree 題目:https://leetcode.com/problems/invert-binary-tree/

Invert Binary Tree   交換二叉樹

public static void main(String[] args) {
		TreeNode treeNode1=new TreeNode(4);
		TreeNode treeNode2=new TreeNode(2);
		TreeNode treeNode3=new TreeNode(7);
		TreeNode treeNode4=new TreeNode(1);
		TreeNode treeNode5=new TreeNode(3);
		TreeNode treeNode6=new TreeNode(6);
		TreeNode treeNode7=new TreeNode(9);
		treeNode1.left=treeNode2;
		treeNode1.right=treeNode3;
		treeNode2.left=treeNode4;
		treeNode2.right=treeNode5;
		treeNode3.left=treeNode6;
		treeNode3.right=treeNode7;
		TreeNode treeNode = invertTree(treeNode1);
		preOrderTraversal(treeNode);

	}

	/**
	 * 先序遍歷樹
	 * @param root
	 * @return
	 */
	public static void preOrderTraversal(TreeNode root){
		if(root!=null){
			System.out.print(root.val+" ");
			preOrderTraversal(root.left);
			preOrderTraversal(root.right);
		}

	}


	public  static TreeNode invertTree(TreeNode root) {
		if(root==null){
			return root;
		}else{
			TreeNode temp=root.left;
			root.left=root.right;
			root.right=temp;
			invertTree(root.left);
			invertTree(root.right);
			return root;
		}
	}