[검지 OFFER] 면접문제 32 - III. 위에서 아래로 두 갈래 나무 인쇄 III
                                            
 10982 단어  검지offer
                    
예를 들어 두 갈래 나무를 주면[3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
다음 단계를 반복한 결과를 반환합니다.
[
  [3],
  [20,9],
  [15,7]
]
팁:
  <= 1000
답변:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root == null) return new ArrayList<List<Integer>>();
        int i = 0;
        List<List<Integer>> l = new ArrayList<List<Integer>>();
        Queue<TreeNode> q1 = new LinkedList<TreeNode>();
        Queue<TreeNode> q2 = new LinkedList<TreeNode>();
        q2.add(root);
        while(!q1.isEmpty() || !q2.isEmpty()){
            List<Integer> k = new ArrayList<Integer>();
            Stack s = new Stack();
            while(!q2.isEmpty()){
                q1.add(q2.poll());
            }
            while(!q1.isEmpty()){
                TreeNode node = q1.poll();
                if(i % 2 != 0) s.push(node.val);
                else k.add(node.val);
                if(node.left != null) q2.add(node.left);
                if(node.right != null) q2.add(node.right);
            }
            while(!s.isEmpty()) k.add((int)s.pop());
            l.add(i, k);
            i++;
        }
        return l;
    }
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
20200326 - 검지offer 면접문제 27: 두 갈래 나무의 거울이솔 위 안에 28문제의 답안이 있는데 어떻게 꼬치는지 모르겠다.간단해....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.