二叉树的镜像

采用非递归方式解决:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.*;

public class Solution {
    List<Integer> list = new ArrayList<>();
    public List<Integer> Mirror(TreeNode root) {
         if (root == null) {
            return null;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node  = stack.pop();
            list.add(node.val);
            //System.out.println(node.val);
            if (node.left != null || node.right != null) {
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
            }
            if (node.left != null) {
                stack.push(node.left);
            }
             if (node.right != null) {
                stack.push(node.right);
            }
            
           
            

        }
        return list;

    }
}

 

posted on 2018-06-10 21:00  我想静静_zjf  阅读(129)  评论(0编辑  收藏  举报

导航