二叉樹前中後序總結遍歷

 https://www.b2bchain.cn/3761.html

原文地址 https://www.b2bchain.cn/3761.html

144.前序

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ans=new ArrayList<>();
      
           helper(root,ans);
​
         return ans;
             
    }
    private void  helper(TreeNode root,List ans){
        if(root==null) return ;
    
            ans.add(root.val);
             helper(root.left,ans);
             helper(root.right,ans);
       
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ans=new ArrayList<>();
        if(root==null) return ans;
        Deque<TreeNode> stack=new ArrayDeque<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode cur=stack.pop();
            ans.add(cur.val);
            if(cur.right!=null){
                stack.push(cur.right);
            }
            if(cur.left!=null){
                stack.push(cur.left);
            }
        }
        return ans;
    }
}

中序94

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
      List<Integer> ans=new ArrayList<>();
      if(root==null) return ans;
      Deque<TreeNode> stack=new ArrayDeque<>();
      while(!stack.isEmpty()||root!=null){
          //入棧一直到最左
          while(root!=null){
              stack.push(root);
              root=root.left;
​
          }
          root=stack.pop();
          ans.add(root.val);
​
          root=root.right;
      }
      return ans;
    }
}

後序145

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        //linkedList 涉及到結果的反轉
       LinkedList<Integer> ans=new LinkedList<>();
       if(root==null) return ans;
       Deque<TreeNode> stack=new ArrayDeque<>();
       stack.push(root);
       while(!stack.isEmpty()){
           TreeNode cur=stack.pop();
           //加到首
           ans.addFirst(cur.val);
            //使用if
           if(cur.left!=null){
                 stack.push(cur.left);
           }
           if(cur.right!=null){
                stack.push(cur.right);
           }
       }
       return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章