Can anyone give a non-recursion way?


  • 0
    K

    There are plenty of way using recursion. Can anyone give out a non-recursion method?


  • 0
    Q
    class Solution {
    public:
        int maxDepth(TreeNode* root) {
          if(root==NULL){
            return 0;
          }
            stack<pair <TreeNode*,int> > s;
            s.push(make_pair(root,1));
            pair <TreeNode*,int> t;
            int ans = 0;
            while(!s.empty()){
              t = s.top();
              s.pop();
              if(t.first->left!=NULL){
                s.push(make_pair(t.first->left,t.second+1));
              }
              if(t.first->right!=NULL){
                s.push(make_pair(t.first->right,t.second+1));
              }
              if(t.second>ans){
                ans = t.second;
              }
            }
            return ans;
        }
    };

  • 0
    X
    This post is deleted!

  • 0
    X
    class Solution(object):
        def maxDepth(self, root):
            nodelist = [root]
            layerlist = [1]
            lastcount = 0
            while len(nodelist):
                curnode = nodelist[0]
                if curnode is not None:
                    nodelist += [curnode.left, curnode.right]
                    layerlist += [layerlist[0]+1, layerlist[0]+1]
                    lastcount = layerlist[0]
                del nodelist[0]
                del layerlist[0]
            return lastcount

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.