ツリートラバーサルシーケンスLeetcode590.N後

タイトル説明

そのノードのトラバースからシーケンス戻った後N分木を、与えられました。

例:

ここに画像を挿入説明

戻り、その後、前順:[5,6,3,2,4,1]。

問題の解決策

第一の補間前順後(javaの)

アイデア:ツリーは頭プラグ先行順いることを確実にするために、同時に、横断されます。(+スタックヘッドプラグ)


/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;
    public Node() {}
    public Node(int _val) {
        val = _val;
    }
    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<Integer> postorder(Node root) {
        LinkedList<Node> stack = new LinkedList<>();
        LinkedList<Integer> output = new LinkedList<>();
        if (root == null) {
            return output;
        }
      stack.add(root);
      while (!stack.isEmpty()) {
          Node node = stack.pollLast();
          output.addFirst(node.val);
          for (Node item : node.children) {
              if (item != null) {
                  stack.add(item);    
              } 
          }
      }
      return output;
    }
}

複雑性分析

  • 時間計算: ザ・ N O(N)
  • 宇宙の複雑さ: ザ・ N O(N)

再帰(Javaの)

アイデア:

class Solution {
    public List<Integer> postorder(Node root) {
        List<Integer> res  =  new ArrayList<Integer>();
        if(root == null) return res;
        for(Node cur:root.children){
            res.addAll(postorder(cur));
        }
        res.add(root.val);
        return res;
    }
}

複雑性分析

  • 時間計算: ザ・ N O(N)
  • 宇宙の複雑さ: ザ・ N O(N)
公開された43元の記事 ウォン称賛20 ビュー1441

おすすめ

転載: blog.csdn.net/Chen_2018k/article/details/105085157