LeetCode:Invert Binary Tree - 反轉二叉樹

一、題目名稱java

Invert Binary Tree(反轉二叉樹)node

二、題目地址code

https://leetcode.com/problems/invert-binary-tree/遞歸

三、題目內容leetcode

英文:get

Invert a binary tree.io

4
   /   \
  2     7
 / \   / \
1   3 6   9

toclass

4
   /   \
  7     2
 / \   / \
9   6 3   1

中文:反轉一顆二叉樹。import

四、解題方法1二叉樹

本題有兩種解題方法,第一種是經過遞歸的方式解決問題,代碼行數少,可讀性強。

Java代碼以下:

/**
 * LeetCode 226 - Invert Binary Tree
 * @文件名稱 Solution.java
 * @文件做者 Tsybius2014
 * @建立時間 2016年2月11日 下午10:34:59
 */
public class Solution {
    /**
     * 翻轉二叉樹
     * @param root 二叉樹的根
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}

五、解題方法2

使用迭代方式解決本問題的Java代碼以下:

import java.util.Stack;

/**
 * LeetCode 226 - Invert Binary Tree
 * @文件名稱 Solution.java
 * @文件做者 Tsybius2014
 * @建立時間 2016年2月11日 下午10:34:59
 */
public class Solution {
    /**
     * 翻轉二叉樹
     * @param root 二叉樹的根
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.peek();
            stack.pop();
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }
        return root;
    }
}

END

相關文章
相關標籤/搜索