LeetCode中级算法 二叉树的锯齿形层次遍历

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

[
  [3],
  [20,9],
  [15,7]
]

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List> zigzagLevelOrder(TreeNode root) {
         
        if(root==null){
          return new ArrayList<>();
        }

        List> result=new ArrayList<>();
        boolean flag=true;

        Stack zstack=new Stack<>();
        Stack ystack=new Stack<>();

        ystack.push(root);

        while (true){
            if(flag){
                //从左开始入栈,出栈按照从右往左
                if (!ystack.empty()){
                    List temp=new ArrayList<>();
                    while (!ystack.empty()){
                        TreeNode tempNode=ystack.pop();
                        temp.add(tempNode.val);
                        
                        if(tempNode.left!=null)
                        zstack.push(tempNode.left);
                        
                        if(tempNode.right!=null)
                        zstack.push(tempNode.right);
                    }
                    
                    if(!temp.isEmpty())
                    result.add(temp);
                    
                    flag=false;
                }else{
                    return result;
                }
            }else{
                //从右开始入栈,出栈按照从左往右
                if (!zstack.empty()){
                    List temp=new ArrayList<>();
                    while (!zstack.empty()){
                        TreeNode tempNode=zstack.pop();
                        temp.add(tempNode.val);
                        
                        if(tempNode.right!=null)
                        ystack.push(tempNode.right);
                        
                        if(tempNode.left!=null)
                        ystack.push(tempNode.left);
                    }
                    
                    if(!temp.isEmpty())
                    result.add(temp);
                    flag=true;
                }else{
                    return result;
                }
            }
        }
    }
}

 

你可能感兴趣的:(JAVA,LeetCode,树)