翻转二叉树

来源:互联网 发布:程序员一天工作几小时 编辑:程序博客网 时间:2024/05/21 02:53

翻转一棵二叉树

样例
  1         1 / \       / \2   3  => 3   2   /       \  4         4
挑战 

递归固然可行,能否写个非递归的?


/**     * 翻转一棵二叉树     * 递归法     * 1. 当前节点为空,直接返回     * 2. 当前节点不为空,交换左右节点     * 3. 分别对左右子树做同样的操作     *     * @param root     */    public void invertBinaryTree1(TreeNode root) {        if (root == null) return;        if (root.left != null && root.right == null) {            root.right = root.left;            root.left = null;        } else if (root.left == null && root.right != null) {            root.left = root.right;            root.right = null;        } else if (root.left != null && root.right != null) {            TreeNode p = root.left;            root.left = root.right;            root.right = p;        }        invertBinaryTree1(root.left);        invertBinaryTree1(root.right);    }    /**     * 非递归     * 将根节点放入栈中,然后不断取出节点,交换该节点的左右儿子,并把左右儿子放入栈中,不断重复,直到栈为空     *     * @param root     */    public void invertBinaryTree(TreeNode root) {        if (root == null) return;        Stack<TreeNode> stack = new Stack<>();        stack.push(root);        TreeNode p = root, q = null;        while (!stack.empty()) {            p = stack.pop();            q = p.left;            p.left = p.right;            p.right = q;            if (p.right != null) {                stack.push(p.right);            }            if (p.left != null) {                stack.push(p.left);            }        }    }