美文网首页
leetcode-tree relevant

leetcode-tree relevant

作者: 爆炸的热水袋 | 来源:发表于2019-10-20 13:35 被阅读0次

一个inorder traverse 的iteration:

TreeNode curr = root;
        while (curr != null || !stack.isEmpty()) {
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            res.add(curr.val);
            curr = curr.right;
        }

先循环左边,左边循环完循环右边,但是右边的node也要循环他的左边,所以要把循环左边的while循环和获得右边node的操作放在同一个循环里,外面再加一个循环,条件在!stack.isEmpty上增加curr!=NULL,这样获得右边node之后,先对右边node进行左循环,在从stack中获取右边node。


Lowest Common Ancester

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==NULL) return NULL;
        else{
            if(root==p) return root;
            if(root==q) return root;
            TreeNode* leftt = lowestCommonAncestor(root->left, p,q);
            TreeNode* rightt = lowestCommonAncestor(root->right, p,q);
            if(leftt==NULL&&rightt==NULL) return NULL;
            if(leftt==NULL) return rightt;
            if(rightt==NULL) return leftt;
            return root;
        }
    }
};

计算p,q和他们的LCA,其实相当于计算p,q,和LCA的LCA,所以可以一层层循环对每个node找下去直到右边两边有一个有p,有一个有q,说明这个intermediate Node就是要找的LCA。

相关文章

  • leetcode-tree relevant

    一个inorder traverse 的iteration: 先循环左边,左边循环完循环右边,但是右边的node也...

  • Relevant

    曾经很惊艳的app,今天打开一看,连data都没有了。 卡片设计有好的地方,每个主题的信息可以关联在一张卡片里,卡...

  • Python relevant

    Good Python tutorial collection Python 入门指南12. 虚拟环境和包Pyth...

  • Leetcode-Tree

    Leetcode 894. All Possible Full Binary Trees.

  • Leetcode-Tree

    Binary Tree 的遍历,Time: O(n), Space: O(n).先序遍历:preorder(nod...

  • AD unix attributes

    For the relevant POSIX attributes (uidNumber, gidNumber, ...

  • 六级乐词150词

    ignite 发光的 incidence 发生 relevant ...

  • Trading-Terminal

    :chart: All content on this page is relevant for Trading ...

  • 01 - Foreword 前言

    The main body of this specification, and the relevant Ann...

  • factor in

    factor something in:include something as a relevant eleme...

网友评论

      本文标题:leetcode-tree relevant

      本文链接:https://www.haomeiwen.com/subject/umrsyctx.html