Leet Code 두 갈래 나무의 앞을 두루 훑어보다

2469 단어
두 갈래 나무를 정해서 앞뒤로 돌아갑니다.예:
 : [1,null,2,3]  
   1
    \
     2
    /
   3 

 : [1,2,3]

비귀속 (가장 뚜렷한 사고방식):
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List list = new ArrayList<>();
        Stack stack = new Stack<>();
        TreeNode cur = root;
        if(cur == null) return list;
        while(cur != null){
            list.add(cur.val);
            stack.push(cur);
            cur = cur.left;
        }
        while(!stack.isEmpty()){
            cur = stack.pop();
            cur = cur.right;
            while(cur != null){
                list.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }
        }
        return list;
    }
    
}

비귀속 (이전 버전의 개선, 코드 간소화):
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List list = new ArrayList<>();
        Stack stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()){
            if(cur != null){
                stack.push(cur);
                list.add(cur.val);
                cur=cur.left;
            }else{
                cur = stack.pop();
                cur = cur.right;
            }
        }
        return list;
    }
    
}

귀속:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List list = new ArrayList<>();
        return test(root,list);
        
    }
    List test(TreeNode root, List list){
        if(root != null){
            list.add(root.val);
            test(root.left,list);
            test(root.right,list);
        }
        return list;
    }
}

좋은 웹페이지 즐겨찾기